I have a List of objects.
eg>
groupId=1 name=name1
groupId=1 name=name2
groupId=1 name=name3
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.
With Java 8 you could use the groupingBy collector:
Map<String, List<MyObject>> map = list.stream()
.collect(Collectors.groupingBy(MyObject::getGroupId));
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With