2

I have a List of objects.

eg>

Object 1

groupId=1 name=name1

Object 2

groupId=1 name=name2

Object 3

groupId=1 name=name3

Object 4

groupId=2 name=name4

Multiple objects in the List have same value for groupId. I need to create Sub-Lists of objects with same groupId. How do I do this in Java.

My Inital thought was to create a HashMap<Integer,List<Object>> but i am unsure about indefinite values of groupIds coming in , which in turn makes me unsure about how to group objects with same groupIds together with groupId as the hashmap's key.

If the groupId's were not to change or increase in the future i could have iterated over the original list and written a switch statement to create required arrays.

Niraj Adhikari
  • 1,678
  • 2
  • 14
  • 28

4 Answers4

8

With Java 8 you could use the groupingBy collector:

Map<String, List<MyObject>> map = list.stream()
               .collect(Collectors.groupingBy(MyObject::getGroupId));
AntoineB
  • 4,535
  • 5
  • 28
  • 61
assylias
  • 321,522
  • 82
  • 660
  • 783
5

I did it this way. I used LinkedHashMap<K,V> as i had to preserve the order of my objects i had sorted according to object's priority value property.

    LinkedHashMap<Group, List<Object>> hashMap=new LinkedHashMap<Group, List<Object>>();        

    for(Object model:objects){

            if(!hashMap.containsKey(model.getGroup())){
            List<Object> list= new ArrayList<Object>();
            list.add(model);
            hashMap.put(Group,list);
        }
        else{
            hashMap.get(model.getGroup()).add(model);
        }
Niraj Adhikari
  • 1,678
  • 2
  • 14
  • 28
2

In Java 8 you can use some filters.

public class A {
    public int groupId;
    public String name;

    public A(int groupId, String name) {
        this.groupId = groupId;
        this.name = name;
    }
}

Filter using Collections API

ArrayList<A> list=new ArrayList();
list.add(new A(2, "tom"));
list.add(new A(2, "rome"));
list.add(new A(1, "sam"));

List<A> filteredlist = list.stream().filter(p -> p.groupId==2).collect(Collectors.toList());
Bruce
  • 8,609
  • 8
  • 54
  • 83
1

I think you need a Map like this -

Map map = new HashMap<Integer, List<String>>();  

Where the key in the HashMap is Integer represents your groupId (ie. - 1, 2, 3 etc) and value (ie - name1, name2 etc) of the HashMap stored at the List of String.

You may use the following steps -

1. Iterate over your four lists.
2. Add each item to a Map construction (eg.- here map) based on the key groupId.

I think this link would be helpful in this context.

Community
  • 1
  • 1
Razib
  • 10,965
  • 11
  • 53
  • 80
  • That was the first thing i thought but I am unsure about the number of groups coming in from the datasource. if i was certain about group count it wouldn't be an issue. – Niraj Adhikari Jul 20 '15 at 17:54