Manu Manu - 1 year ago 66
Java Question

Split an Arraylist into multiple lists for a same element (String) - JAVA

I have an ArrayList of similar objects. I have to split the lists into multiple lists based on a similar element (String)

This is an example, the ArrayList have inside objects, not (String, Integer)

Here is the sample List:

ArrayList{ {'Milk', 12}, {'Apple', 60}, {'Coffe', 87}, {'Pear', 39}, {'Coffe', 87},
{'Milk', 99}, {'Apple', 43}, {'Milk', 20} }

Result should be:

List 1:

ArrayList{ {'Milk', 12}, {'Milk', 99}, {'Milk', 20} }


ArrayList{ {'Apple', 60}, {'Apple', 43} }


ArrayList{ {'Coffe', 87}, {'Coffe', 87} }


ArrayList{ {'Pear', 39} }

Somebody would to give me a easier way doing this??

Answer Source

Use Multimaps from package


Map<String,Collection<Map.Entry<String,Integer>>>map=Multimaps.index(entries,new GroupFunction()).asMap();

class GroupFunction implements Function<Map.Entry<String,Integer>, String> {
    public String apply(Map.Entry<String,Integer>input) {
        return input.getKey();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download