The Stream.collect(supplier, accumulator, combiner)
method can be used to accomplish this. The following would create a MultivaluedMap
from a stream and an arbitrary keyFn
& valueFn
Function
pair:
MultivaluedMap<K, V> multimap = list.stream().collect(
MultivaluedHashMap::new,
(multimap, input) -> multimap.add(keyFn.apply(input), valueFn.apply(input)),
MultivaluedMap::putAll);
Per the Stream.collect
Javadocs:
Performs a mutable reduction operation on the elements of this stream. A mutable reduction is one in which the reduced value is a mutable result container, such as an ArrayList
, and elements are incorporated by updating the state of the result rather than by replacing the result.
Since streams can be processed in parallel, multiple interim MultivaluedMap
instances might be created, each with a subset of the Stream
's values included in it. The interim multimaps would be combined into a single MultivaluedMap
by using putAll
to put all elements from the interim multimaps into one of the multimaps, which is then returned as the final result.
As a specific example, the following code could be used to create a MultivaluedMap
from a Stream<String>
where the key was the length of the strings, and the values were the strings themselves:
Stream<String> strings = Stream.of("Ant", "Ball", "Cat", "Ant", "House");
MultivaluedMap<Integer, String> stringsByLength = strings.collect(
MultivaluedHashMap::new,
(multimap, input) -> multimap.add(input.length(), input),
MultivaluedMap::putAll
);
System.out.println(stringsByLength); // {3=[Ant, Cat, Ant], 4=[Ball], 5=[House]}
This creates new multimaps using new MultivaluedHashMap()
, adds elements to the multimaps using MultivaluedMap.add()
, and combines multimaps together using MultivaluedMap.putAll()
.