In problem statement, I have 'n' number of families with 'n' number of family members.
eg:
John jane (family 1)
tiya (family 2)
Erika (family 3)
I have to assign all members in such a way that person should not pair with the his family member.
and output should be:
John => tiya
jane => Erika
tiya => jane
Erika => john
I have created the object Person(name ,familyID, isAllocated).
Created the list and added personName_id in this this.
I am thinking to use the map for association. So that john_1 will be key and tiya_2 will be value.
I am failing to associate those pairs through map. How can I shuffle the members it the list.
Also, It would be nice if anyone could suggest me the better solution.
Code:
Getting person:
public static List getperson()
{
Scanner keyboard = new Scanner(System.in);
String line = null;
int count = 0;
List <Person> people = new ArrayList<>();
while(!(line = keyboard.nextLine()).isEmpty()) {
String[] values = line.split("\\s+");
//System.out.print("entered: " + Arrays.toString(values) + "\n");
int familyid = count++;
for(String name :values)
{
Person person = new Person();
person.setFamilyId(familyid);
person.setName(name);
person.setAllocated(false);
people.add(person);
}
}
return people;
}
Mapping:
public static List mapGifts(List pesonList)
{
Map<String , String> personMap = new HashMap<String , String>();
Iterator<Person> itr = pesonList.iterator();
Iterator<Person> itr2 = pesonList.iterator();
List<String> sender = new ArrayList<>();
while(itr.hasNext())
{
Person p = itr.next();
sender.add(p.getName()+"_"+p.getFamilyId());
personMap.put(p.getName()+"_"+p.getFamilyId(), "");
// p.setAllocated(true);
}
while(itr2.hasNext())
{
/*if(p.isAllocated())
{*/
// Separate Sender name and id from sender list
//check this id match with new p1.getFamilyId()
for(String sendername :sender)
{
// System.out.println("Sender "+sendername);
personMap.put(sendername, "");
String[] names = sendername.split("_");
String part1 = names[0]; // 004
String familyId = names[1]; // 004
Person p2 = itr2.next();
System.out.println(p2.getFamilyId() +" "+familyId +" "+p2.isAllocated());
if(p2.isAllocated())
{
for ( String value: personMap.values()) {
if ( value != sendername) {
}
}
}
if( p2.getFamilyId() != Integer.parseInt(familyId))
{
// add values in map
}
}
break;
// Person newPerson = personLists.get(j);
}
for (Iterator it = personMap.entrySet().iterator(); it.hasNext();)
{
Map.Entry entry = (Map.Entry) it.next();
Object key = entry.getKey();
Object value = entry.getValue();
System.out.println("Gifts "+key+"=>"+value);
}
return pesonList;
}
Thanks
From what I've read, you only care that you match people. How they match doesn't matter. That said, I'll assume you have a list of FamilyID's, and a list of names of everyone, and that you can sort the list of people according to family IDs.
Let's call them:
List<FamilyID> families; and
LinkedList<Person> people;, respectively. (You can make FamilyID an enumerated class)
We need two hashmaps. One to generate a list (essentially an adjacency list) of family members given a familyID:
HashMap<FamilyID, List<Person>> familyMembers; ,
and one to generate a list of sender(key) and receiver(value) pairs:
HashMap<Person, Person> pairs;
A useful function may be that, when given a person and their family ID, we can find the next available person who can receive from them.
String generateReceiver(Person newSender, FamilyID familyID);
Implementation of this method should be pretty straightforward. You can iterate through the list of people and check to see if the current person is not a family member. If that condition passes, you remove them from the "people" list so you don't try to iterate through them again. If you're using a linked list for this, removal is O(1) since you'll already have the reference. Worst case on traversals the list is n + n - 1 + ... + 2 times to get O(n^2) time efficiency (i.e. you have one large family and many small ones). Work around that would be to ditch the LinkedList, use an Array-based list, and keep a separate array of index values corresponding to each "currently available receiver of a specified family". You'd initialize these values as you added the people from each family to the people list (i.e. start of family 1 is index "0"; if family 1 has 2 people, start of family 2 would be index "2"). This would make the function O(1) time if you just incremented the current available receiver index everytime you added a sender-receiver pair. (Message me if you want more details on this!)
Last but not least, the loop is doing this for all people.
for (List<Person> family : familyMembers)
for (Person person : family)
{
// get the next available receiver who is not a family member
// add the family member and its receiver to "pairs" hash
}
Note that the above loop is pseudocode. If you're wondering if you would generate conflicting receiver/senders with this method, you won't. The list of people is essentially acting as a list of receivers. Whichever way you implement the people list, the generateReceiver(...)eliminates the chance that the algorithm would see a faulty-receiver. Per efficiency, if you do the array based implementation then you're at O(N) time for generating all pair values, where N is the total number of people. The program itself would be O(N) space as well.
Of course, this is all based on the assumption you have enough people to match for sender-receiver pairs. You'd need to add bells and whistles to check for special cases.
Hope this helps! Good luck!
Related
I am working on the following problem:
In a room with people, we will define two persons are friends if they
are directly or indirectly friends. If A is a friend with B, and B is
a friend with C, then A is a friend of C too. A group of friends is a
group of persons where any two persons in the group are friends. Given
the list of persons that are directly friends, find the smallest group
of friends..
Example:
Input:
1<->6
2<->7
3<->8
4<->9
2<->6
3<->5
Groups:
1-6-2-7
3-8-5
4-9
The number of people in the smallest group is 2 i.e. 4-9 so we should return 2.
I came up with the code below but I don't understand how to use this holder map now to get the required output. I am kinda confused here. What is the best way to solve this problem?
private static int findGroups(final List<List<Integer>> inputs) {
if (inputs == null || inputs.isEmpty()) {
return 0;
}
int count = Integer.MAX_VALUE;
Map<Integer, List<Integer>> holder = new HashMap<>();
for (List<Integer> input : inputs) {
// storing it in bidirectional way in the map
List<Integer> l =
holder.containsKey(input.get(0)) ? holder.get(input.get(0)) : new ArrayList<Integer>();
l.add(input.get(1));
holder.put(input.get(0), l);
List<Integer> l1 =
holder.containsKey(input.get(1)) ? holder.get(input.get(1)) : new ArrayList<Integer>();
l1.add(input.get(0));
holder.put(input.get(1), l1);
}
System.out.println(holder);
// use holder map to get the smaller group here?
return count;
}
Looks like I need to use recursion here to get smaller groups?
Is there any better way to solve this problem?
A better approach is to use a disjoint-set data structure:
First, compute the "groups of friends" as a disjoint-set data structure:
Initialize a disjoint-set data structure where the elements of the sets will be the people in the room.
For each person p in the room:
Call MakeSet(p) to initialize a "group of friends" containing just that person.
For each direct friendship p1↔p2:
Call Union(p1, p2) to unify the "group of friends" that contains p1 with the one that contains p2.
Next, compute the sizes of the "groups of friends" as a map:
Initialize a map where the keys will be some of the people in the room (namely, the representatives of their respective "groups of friends") and the values will be numbers (namely, the sizes of the various "groups of friends").
For each person p1 in the room:
Call Find(p1) to find the representative p2 of that person's "group of friends".
If the map does not already contain a value for the key p2, insert the value 0 for that key.
Increment the value for the key p2.
Lastly, compute the result:
Initialize a result to a large value, e.g. the number of people in the room.
For each value (= size of a "group of friends") in the map:
If this value is less than the result, set the result equal to this value.
Return the result.
By the way, the technical name for the operation you're performing is transitive closure: the "are friends" relation is the transitive closure of the "are directly friends" relation. (However, the algorithms described at the Wikipedia article for that are not optimal for your problem, because they don't take advantage of the fact that your relation is symmetric.)
Here's some code, I've wrote out of curiousity about your problem. I don't know much about graphs, but it uses recursion, like you requested.
Basically you go through the input and for every person, you create an ArrayList<Integer>. In that array are the people who are that person's immediate friends. For instance, for 1: {6}, for 2: {7, 6}, for 3: {8, 5}. Then, to get all friends of person 2, you create a compoud ArrayList<Integer> array by getting together arrays for person 7 and 6 (excluding duplicates). So, the recursion could be used in a way that a function getAllFriends(Integer person) would have to return the getAllFriends(Integer person2) for that person's immediate friends as well.
So, the code could look like something like this:
public class Test {
public static void main(String[] args) throws Exception {
String input = "1<->6\n" +
"2<->7\n" +
"3<->8\n" +
"4<->9\n" +
"2<->6\n" +
"3<->5";
HashMap<Integer, ArrayList<Integer>> friends = processInput(input); //getting data from the input string and storing it in a structured way
System.out.println(getAllFriends(1, friends, new ArrayList<Integer>(){{add(1);}})); //output: [1, 6, 2, 7]. Double brackets create an anonymous inner class, you add to the result the id of a person whose friends you're collecting
}
public static HashMap<Integer, ArrayList<Integer>> processInput(String input) throws Exception {
HashMap<Integer, ArrayList<Integer>> result = new HashMap<>();
BufferedReader bufReader = new BufferedReader(new StringReader(input));
String line=null;
while( (line=bufReader.readLine()) != null )
{
Integer personLeft = Integer.valueOf(line.substring(0, line.indexOf("<")));
Integer personRight =Integer.valueOf(line.substring(line.indexOf(">")+1, line.length()));
System.out.println(personLeft + ": " + personRight);
if (!result.containsKey(personLeft)) {
result.put(personLeft, new ArrayList<Integer>());
}
result.get(personLeft).add(personRight);
if (!result.containsKey(personRight)) {
result.put(personRight, new ArrayList<Integer>());
}
result.get(personRight).add(personLeft);
}
return result;
}
public static ArrayList<Integer> getAllFriends(Integer person, HashMap<Integer, ArrayList<Integer>> friends, ArrayList<Integer> result) {
for (Integer personFriend: friends.get(person)) {
if (!result.contains(personFriend)) {
result.add(personFriend); //add a person, if it wasn't added before
getAllFriends(personFriend, friends, result); //check out that person's friends
}
}
return result;
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Given a list/array of strings:
document
document (1)
document (2)
document (3)
mypdf (1)
mypdf
myspreadsheet (1)
myspreadsheet
myspreadsheet (2)
How do I remove all the duplicates but retain only the highest copy number?
Ending result to be:
document (3)
mypdf (1)
myspreadsheet (2)
You put in a broad question, so here comes an unspecific (but nonetheless) "complete" answer:
Iterate over all your strings to identify all lines that contain braces.
In other words: identify all the strings that look like "X (n)"
Then, for each "different" X that you found, you can iterate the list again; so that you can find all occurrences of "X", X (1)", .. and so on
Doing so will allow you to detect the maximum n for each of your Xes.
Push that "maximum" "X (n)" into your results list.
In other words: it only takes such a simple receipt to solve this problem; now it only takes your time to turn these pseudo-code instructions into real code.
For the record: if the layout of your file is really as shown above, then things become a bit easier - as it seems that your numbers are just increasing. What I mean is:
X (1)
X (2)
X (3)
is easier to treat than
X (1)
X (3)
X (2)
As in your case, it seems save to assume that the last X(n) contains the largest n. Which makes using a HashMap (as suggested by cainiaofei) a nice solution.
an alternative solution
use a HashMap the key is the name (e.g. the name of document document (1)
document (2) document (3) are all document)
which can be implement by this code str.substring(0,str.indexOf('(')).trim()
and the value is the times that key present, at last traverse the map get the key that corresponding value is max and the result is key(value-1)
I would advice you to use a dictionnary :
Map<String, Integer> dict = new HashMap<>();
for (String s : listOfInput){
String name = s.split(" ")[0];
String version = s.split(" ")[1].charAt(1);
if(dict.get(name)!=null){
if (Integer.parseInt(version) < dict.get(name)){
continue;
}
}
dict.put(name, version);
}
The data would be at the end in the dictionary:
key | value
document | 3
mypdf | 1
myspreadsheet | 2
This is a simple solution by making use of a Map. First you loop through your list, you split the String, and you add it to the map with the name as the key, and what's inside the paranthesis as a value. And for each entry you check if the key already exists. And if the key exists you compare the value and you add the next entry to the map if the value is bigger than what's already stored. At the end you loop through the map and get your list.
This should probably work with any kind of input. I think...
Of course this can be done better than this. If anybody has suggestions, please feel free to share them.
public static void main(String[] args) {
List<String> list = Arrays.asList("document", "document (1)", "document (2)", "document (3)", "mypdf (1)", "mypdf", "myspreadsheet (1)",
"myspreadsheet", "myspreadsheet (2)");
Map<String, Integer> counterMap = new HashMap<>();
List<String> newList = new ArrayList<>();
for (String item : list) {
if (item.indexOf(')') != -1) {
String namePart = item.substring(0, item.indexOf('(')).trim();
Integer numberPart = Integer.parseInt(item.substring(item.indexOf('(') + 1, item.indexOf(')')));
Integer existingValue = counterMap.get(namePart);
if (existingValue != null) {
if (numberPart > existingValue) {
counterMap.put(namePart, numberPart);
}
} else {
counterMap.put(namePart, numberPart);
}
} else {
newList.add(item);
}
}
Iterator<Entry<String, Integer>> iterator = counterMap.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, Integer> next = iterator.next();
String key = next.getKey();
Integer value = next.getValue();
if (newList.contains(key)) {
newList.remove(key);
}
newList.add(key + " (" + value + ")");
}
System.out.println(newList);
}
Here is a possible approach, but this will only work if the version number doesn't exceed 9 (*) :
1) Sort the list in reverse order, so that the most recent version appears first
(*) The sorting being based on alphabetical order , you should be quite fine unless your version number exceeds one digit.Because 10 for instance, appears before 9 with an alphabetical sorting.
Your list will turn into :
myspreadsheet (2)
myspreadsheet (1)
myspreadsheet
mypdf (1)
mypdf
document (3)
document (2)
document (1)
document
2) Iterate on the list, and only keep the first occurence of a given document (i.e the most recent thanks to the reverse sorting)
3) If you want to, sort back the remaining list to a more natural ordering
List<String> documents = new ArrayList<String>();
documents.add("document");
documents.add("document (1)");
documents.add("document (2)");
documents.add("document (3)");
documents.add("mypdf (1)");
documents.add("mypdf");
documents.add("myspreadsheet (1)");
documents.add("myspreadsheet");
documents.add("myspreadsheet (2)");
// 1) Sort in reverse order, so that the most recent document version appears first
Collections.sort(documents, Collections.reverseOrder());
String lastDocumentName = "";
ListIterator<String> iter = documents.listIterator();
// 2)
while (iter.hasNext()) {
String document = iter.next();
// Store the first part of the String , i.e the document name (without version)
String firstPart = document.split("\\s+")[0];
// Check if this document is a version of the last checked document
// If it is the case, this version is anterior, remove it from the list
if (lastDocumentName.equals(firstPart)) {
iter.remove();
}
// Store this document's name as the last one checked
lastDocumentName = firstPart;
}
// 3) Sort back to natural order
Collections.sort(documents);
for (String doc : documents) {
System.out.println(doc);
}
Let's utilize the Stream API to group our documents and simply pick the newest revision by sorting Strings by the revision number. Keep in mind that those static methods were implemented poorly because you did not give us too much information about the naming strategy but the idea should be clear.
Algorithm:
Group revisions of the same String together
Pick the number with the highest version from each group
Solution:
Map<String, List<String>> grouped = input.stream()
.collect(Collectors.groupingBy(preprocessedString(), Collectors.toList()));
List<String> finalResult = grouped.entrySet().stream()
.map(e -> e.getValue().stream()
.max(Comparator.comparing(revisionNumber())).get()) //at this point we have at least one element
.collect(Collectors.toList());
}
Helper parsing functions:
private static Function<String, Integer> revisionNumber() {
return s -> s.contains("(") ? Integer.valueOf(s.substring(s.indexOf('(') + 1, s.indexOf(')'))) : 0;
}
private static Function<String, String> preprocessedString() {
return s -> s.contains("(") ? s.substring(0, s.lastIndexOf("(")).trim() : s.trim();
}
Input:
List<String> input = Arrays.asList(
"document",
"document (1)",
"document (2)",
"document (3)",
"mypdf (1)",
"mypdf",
"myspreadsheet (12)",
"myspreadsheet",
"myspreadsheet (2)",
"single");
Result:
[single, myspreadsheet (12), document (3), mypdf (1)]
We do not need actually to know if the element contains more then one whitespace or whatever. We can aways start from the end and check if the elements is duplicate or not (see if there is a ")" or not).
Also interating once through the List is enough to get all the information we need. Assuming that, I am providing a solution which saves the highest appearance value as a VALUE in a Map which map will have as KEYs all elements in the given input list.
After that you can create your result List with one more iteration through the Map.
public List<String> removeDuplicates(List<String> inputArray) {
Map<String, Integer> map = new HashMap<String, Integer>();
List<String> result = new ArrayList<String>();
int numberOfOcurences = 0;
for (int i = 0; i < inputArray.size(); i++) {
String element = inputArray.get(i);
if (element.charAt(element.length() - 1) == ')') {
numberOfOcurences = Character.getNumericValue(element.charAt(element.length() - 2));
element = element.substring(0, element.length() - 4);
} else {
numberOfOcurences = 0;
}
if (map.isEmpty()) {
map.put(element, numberOfOcurences);
} else {
if (null != map.get(element) && map.get(element) < numberOfOcurences) {
map.put(element, numberOfOcurences);
} else if (null == map.get(element)) {
map.put(element, numberOfOcurences);
}
}
}
for (String a : map.keySet()) {
result.add(a + " (" + map.get(a)+ ")");
}
return result;
}
Set<T> mySet = new HashSet<T>(Arrays.asList(Your));
I have found that from another user of stackoverflow, try if it works. Good Luck :)
So I'm doing a Star Trek themed project where I need to take a list of crew members and the planets they've visited and generate a log report for Starfleet.
For example this...
Guinan,Drema IV
Picard,Gamalon V
Barclay,Valo III
Riker,Theydat IV
Pulaski,Alpha Moon
Troi,Tessen III
...
Needs to become this
Acamar III:
B. Crusher 11
Barclay 6
Data 15
Gomez 3
Guinan 4
Lefler 5
O'Brien 12
Ogawa 4
Picard 5
Pulaski 14
Riker 12
Troi 9
W. Crusher 4
Worf 14
Yar 3
...
To do this I need to use a generic structure that automatically sorts the incoming data so I decided to use a Tree Map of 15-element int arrays to store the number of visits each crew member has made to a given planet.
My question is, since I am very new to Java, how would I get a value from an array element inside the tree map and update the value inside a given array element? My problem is that all the examples I can find about working with Tree Map either don't involve arrays inside of them or don't show how to get a value and update values after the first insertion. Below I've given my current psuedocode with my best guess as to how to accomplish this. If anyone knows of a way to do this, or a better method entirely please suggest it.
P.S. I'm going to implement the loop I need after I can get a single iteration written correctly
EDIT: For clarity, each element of the 15-element int array corresponds to a crew member so for example Data would be array[2] and Yar would be array[14]
import java.util.*;
public class TreeMapDemo {
public static void main(String args[]) {
// Create a hash map
TreeMap tm = new TreeMap();
int indexDesired;
int visits;
String planetNameVariable;
String crewMemberName;
//Scan input using Scanner and assign planet name and crew name to
//correct variables (code provided by instructor)
// Put elements to the map
//if(planet doesn't already exist in tm)
tm.put(planetNameVariable, new int[14]);
//Decides which element of the array must be incremented
indexDesired = crewToIndex(crewMemberName);
//Increments visit count of crewMemberName on planetNameVariable
visits = //How do I get the value of the array associated with planetNameVariable at indexDesired?
tm.put(planetNameVariable, int[indexDesired] = visits + 1 //How do I insert into an array element here?);
// Get an iterator
Iterator i = set.iterator();
// Display element
// Code not designed yet
}
}
You can something like this. Here you have to put array in map only once because after that you will get only reference so if you modify that it will be modified in map as well.[shallow copy]
int visits[] = null;
// Increments visit count of crewMemberName on planetNameVariable
visits = tm.get(planetNameVariable);
if (visits == null) {
tm.put(planetNameVariable, new int[14]);
visits = tm.get(planetNameVariable);
}
visits[indexDesired]++;
// Get an iterator
Iterator<String> iterator = tm.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
int[] temp = tm.get(key);
if (temp != null) {
for (int i = 0; i < temp.length; i++) {
System.out.println(key + " " + temp[i]);
}
}
}
I have an arraylist with bankcustomers. Some customers occur more than once (this happens if they have more than one account).
Now I want to print all the customers, but if then occur more than once I only want to print them once.
Heres is my non working code. As it is now it prints the whole list. How can I add code to only print duplicates once?
public void showCustomers() {
private ArrayList<Customer> customers = new ArrayList<Customer>();
for(Customer c: customers) {
System.out.println("First name: " + c.getFirstname());
System.out.println("Last name: " + c.getLastname());
System.out.println("Customer number: " + c.getNumber());
for(Account a : c.getAccounts()) {
System.out.println("Account number: " + a.getAccountId());
}
}
}
I prefer not to use HashSet (if it's not neccesary). I'm trying to learn ArrayLists now.
Add all your elements to a Set:
for (Customer c: new HashSet<Customer>(customers)) {
From the linked Javadoc:
A collection that contains no duplicate element
Whenever you need need to avoid duplicates, think Set
List<String> lst = Arrays.asList("Foo", "Foo", "Bar", "Baz");
for(String s : new HashSet<>(lst)) {
System.out.println(s);
}
If the Customer class already implements hashCode and equals in the way you expect it you can just use a Set.
Set<Customer> uniqueCustomers = new HashSet<Customer>(customers);
if you need to keep the original order of the elements in the List use a LinkedHashSet
Set<Customer> uniqueOrderedCustomers = new LinkedHashSet<Customer>(customers);
if the Customer class does not implement hashCode and equals or you can't implement it, because you don't have the sources, use a TreeSet and implement a Comparator.
Optimally, you'll want to create a parallel array within the showCustomers() method.
Have the array contain a relative boolean value.
Within the for(Customer c: customers) iteration create (nest) a conditional statement (an if, else).
From within the conditional, acquire the value at the nth index of the parallel array.
If the current value is false set it to true and print out to the console.
If the current value is true, then call the continue statement to have the iteration go to the next item (and not print to the console).
The following will print the first Customer of the duplicate or multiple entries:
public void showCustomers() {
// Visibility of variables in class methods is irrelevant
// All variables/values created within a method will only be
// accessible from within it's scope
/*private*/ ArrayList<Customer> customers = new ArrayList<Customer>();
// Create a parallel list
List<Boolean> customers_b = new ArrayList<Boolean>(customers.size());
// Use this value to hold the index of your current item
int n = 0;
for(Customer c: customers) {
if(customers_b.get(n) == false)
{
System.out.println("First name: " + c.getFirstname());
System.out.println("Last name: " + c.getFirstname());
System.out.println("Customer number: " + c.getNumber());
for(Account a : c.getAccounts()) {
System.out.println("Account number: " + a.getAccountId());
}
customers_b.set(n, true);
n++;
}
else
{
n++;
continue;
}
}
}
convert your list into a Hashset and this will do the trick, since hashsets doesn't allow duplicate values to be stored but in case of HashMap and if there's a duplicate, it replaces the old value with the new one.
I have an ArrayList containing Objects, these objects have multiple values.
Now I would like to split up this list in to mulptiple lists depeding on an int value in the objects.
So if for example:
2 Objects have an int with value 1
3 Objects have an int with the value 3
So the arraylist has 5 objects, and I'd like to get:
2 Arraylists, 1 with the first objects en 1 with the second objects (more if there are more different int values)
Sorry if it is confusing..
First create a cache like this: Map<Integer, List<YourObjectType>>
Then cycle through each of your objects, and use your integer to access the above Map, if the value is null, create a new List and put it in the Map, then add your object to the List.
The end result would be a map with two entries, each containing a list of entries with the integer from your object being the discriminator.
Here's the code:
Map<Integer, List<YourObject>> cache = new HashMap<Integer, List<YourObject>>();
for (YourObject yo : yourObjectListArrayWhatever) {
List<YourObject> list = cache.get(yo.getIntegerValue());
if (list == null) {
list = new ArrayList<YourObject>();
cache.put(yo.getIntegerValue(), list);
}
list.add(yo);
}
How do you store an int value in Object? I'm sure you have an implementation that is derived from Object and in that case you should use generecity at a lower point of the hierarchy.
Say you have a class Person with an int value and then subclasses Man extends Person and Woman extends Person and you populate this ArrayList with men and women, you would do so like so:
List<Person> pList = new ArrayList<Person>();
Now, in your Person class you should have a get-method for the int value. For example if the int value is the person's age:
public int getAge() { return age; }
Then, to finally answer your question I would go about like so:
List<Person> firstList = new ArrayList<Person>();
List<Person> secondList = new ArrayList<Person>();
for (Person person:pList) {
if (person.getAge()==1) {
firstList.add(person);
}
else if (person.getAge()==3) {
secondList.add(person);
}
}//for
I hope I answered your question adequately.