1

I have an ArrayList of MyClass and I need to extract multiple lists from it according to the repetition of a property of the class.

MyClass:

public class MyClass{
    private int ID;
    private String Name;
    private String Position;

    public MyClass(int ID, String name, String position){
        this.ID = ID;
        Name = name;
        Position = position;
    }
}

Example:

In my ArrayList I have 5 objects:

ID = 0, Name = "Name 0", Position = "G1.1";
ID = 1, Name = "Name 1", Position = "G2.1";
ID = 2, Name = "Name 2", Position = "G1.1";
ID = 3, Name = "Name 3", Position = "G1.1";
ID = 4, Name = "Name 4", Position = "G2.1";

From this list I'll create 2 ArrayLists:

ArrayList 1 (Where Position = "G1.1")
    ID = 0, Name = "Name 0", Position = "G1.1";
    ID = 2, Name = "Name 2", Position = "G1.1";
    ID = 3, Name = "Name 3", Position = "G1.1";
ArrayList 2 (Where Position = "G2.1")
    ID = 1, Name = "Name 1", Position = "G2.1";
    ID = 4, Name = "Name 4", Position = "G2.1";

The main list is created dynamically, so I don't know what will be the positions I will need to create to get the items.

2
  • What have you tried? Could you show what you have done so far? Commented Mar 30, 2017 at 17:18
  • I don't understand what you want to do. Maybe you could assign the new ArrayLists to a HashMap where the keys are the positions? Commented Mar 30, 2017 at 17:21

2 Answers 2

1

You could collect the items together into a Map like this:

Map<String, List<MyClass>> grp = l.stream().collect(Collectors.groupingBy(o -> o.Position));
Sign up to request clarification or add additional context in comments.

Comments

0

Try using a HashMap.

Map<String, List<MyClass>> hm = new HashMap<String, List<MyClass>>();
for(MyClass obj : OrignalList){
    if(null != hm.get(obj.Position)){
         String pos = obj.Position;
         hm.put(pos, hm.get(pos).add(obj));
    }else {
         List<MyClass> temp = new ArrayList<MyClass>();
         temp.add(obj);
         hm.put(obj.Position, temp);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.