Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap<Key,List<Object>> from list of objects containing same property

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.

like image 848
Niraj Adhikari Avatar asked Dec 07 '25 16:12

Niraj Adhikari


2 Answers

With Java 8 you could use the groupingBy collector:

Map<String, List<MyObject>> map = list.stream()
               .collect(Collectors.groupingBy(MyObject::getGroupId));
like image 157
assylias Avatar answered Dec 09 '25 17:12

assylias


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);
        }
like image 31
Niraj Adhikari Avatar answered Dec 09 '25 16:12

Niraj Adhikari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!