Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

java - How can a stream be collected into a JAX-RS MultivaluedMap?

How can a Stream of items be collected into a MultivaluedMap? The built-in Java Map collectors do not work well for this purpose, since they expect to operate on the list type of the map (K,List<V>), rather than the type of the MultivaluedMap (<K,V>).

question from:https://stackoverflow.com/questions/65830814/how-can-a-stream-be-collected-into-a-jax-rs-multivaluedmap

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...