Is there a way to do something like this in Java 8? I have the following interface:
public interface MyInterface{
String groupId();
Integer value();
}
I want to write the following method
public static Map<String, List<Integer>> groupByGroupId(Collection<MyInterface> mis){
//...
}
The thing is I cannot just do map
on the stream as that I lose MyInterface
information.
mis.stream().map(MyInterface::value) // lose groupId
Also it's unacceptable to iterate over the collection twice. I mean I could apply groupingBy to get Map<String, MyInterface>
mis.stream.collect(
groupingBy(
MyInterface::groupId
)
)
But with such approach I have to iterate over the resulting map to get what I want. Maybe there is something I could use with
groupingBy(classifier, downstreamCollector)
But could not find a collector which collects and does mapping while collecting. Is there anything in JDK
to achieve this without lots pain?