简体   繁体   中英

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.

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);
        }

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.

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM