Manu Manu - 7 months ago 4
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} }


List2:

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


List3:

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


List4:

ArrayList{ {'Pear', 39} }


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

Answer

Use Multimaps from com.google.common.collect package

example

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

class GroupFunction implements Function<Map.Entry<String,Integer>, String> {
    @Override
    public String apply(Map.Entry<String,Integer>input) {
        return input.getKey();
    }
}
Comments