Of course, perhaps, and even easier with Guava :) Use Multimaps.index (Iterable, Function) :
ImmutableListMultimap<E, E> indexed = Multimaps.index(list, groupFunction);
If you give a specific use case, it would be easier to show it in action.
Example from the docs:
List<String> badGuys = Arrays.asList("Inky", "Blinky", "Pinky", "Pinky", "Clyde"); Function<String, Integer> stringLengthFunction = ...; Multimap<Integer, String> index = Multimaps.index(badGuys, stringLengthFunction); System.out.println(index);
prints
{4=[Inky], 6=[Blinky], 5=[Pinky, Pinky, Clyde]}
In case GroupFunction is defined as:
GroupFunction<String> groupFunction = new GroupFunction<String>() { @Override public String sameGroup(final String s1, final String s2) { return s1.length().equals(s2.length()); } }
then it translates to:
Function<String, Integer> stringLengthFunction = new Function<String, Integer>() { @Override public Integer apply(final String s) { return s.length(); } }
what is possible stringLengthFunction implementation used in the Guava example.
Finally, in Java 8, the entire snippet can be even simpler, since lambas references and methods are short enough to be nested:
ImmutableListMultimap<E, E> indexed = Multimaps.index(list, String::length);
For a clean Java 8 example (without Guava) using Collector.groupingBy , see Jeffrey Bosboom's answer , although there are few differences in this approach:
- it does not return an
ImmutableListMultimap , but rather a Map with Collection values, There are no guarantees on the type, variability, serializability or security of the flows of the returned card ( source ),
- it is a bit more verbose than the Guava + method reference.
EDIT . If you don't need indexed keys, you can get grouped values:
List<List<E>> grouped = Lists.transform(indexed.keySet().asList(), new Function<E, List<E>>() { @Override public List<E> apply(E key) { return indexed.get(key); } });
which gives you a Lists<List<E>> view, the contents of which can be easily copied into an ArrayList or simply used as is, as you wanted in the first place. Also note that indexed.get(key) ImmutableList .
EDIT 2 : as Peter Gladkikh mentions in the comment below , if Collection<List<E>> enough, the example above might be simpler:
Collection<List<E>> grouped = indexed.asMap().values();