Commit two lists in immutable multimar in Java 8 using Guava?

The for loop looks like

ImmutableListMultiMap.<Key, Value>Builder builder 
    = ImmutableListMultiMap.<Key, Value>newBuilder();
for (int i = 0; i < Math.min(keys.length(), values.length()); i++) {
  builder.put(keys.at(i), values.at(i));
}

A possible first step in Guava / Java 8 is

Streams.zip(keys, values, zippingFunction)

I think I zippingFunctionshould return a map entry, but there is no publicly constructed list entry. Thus, the “most” functional way I can write this is with the zipping function, which returns a pair that I'm not sure about Guava, or returns a list of two elements, which is a mutable type that does not have the proper relationship. make up exactly 2 elements.

This would be desirable if I could create a map entry:

Streams.zip(keys, values, zippingFunction)
.collect(toImmutableListMultimap(e -> e.getKey(), e.getValue())

, , , zip . , ?

+4
3

, ( , , ). , , :

ImmutableListMultimap.Builder<Key, Value> builder = ImmutableListMultimap.builder();
for (int i = 0; i < Math.min(keys.size(), values.size()); i++) {
  builder.put(keys.get(i), values.get(i));
}
return builder.build();

, " ", , "" ​​multimap. , " ", , JDK SimpleImmutableEntry Guava Maps.immutableEntry, ( , Pair, , , JDK, Guava.

Streams#zip , :

Streams.zip(keys.stream(), values.stream(), SimpleImmutableEntry::new)
    .collect(toImmutableListMultimap(Map.Entry::getKey, Map.Entry::getValue));

"" Java, , , jOOL Seq.zip, :

    Seq.zip(keys, values, SimpleImmutableEntry::new)
        .collect(toImmutableListMultimap(Map.Entry::getKey, Map.Entry::getValue));

StreamEx, EntryStream - .

+3

, :

Map<Key, Value> map = IntStream.range(0, Math.min(keys.size(), values.size()))
    .boxed()
    .collect(toImmutableListMultimap(i -> keys[i], i -> values[i]));
+5

, ! (, Integer):

Streams.zip(keys.stream(), values.stream(), AbstractMap.SimpleImmutableEntry::new)
                .collect(toImmutableListMultimap(Map.Entry<Integer, Integer>::getKey,
                        Map.Entry<Integer, Integer>::getValue)
                );

- , . . , collect:

Streams.zip(keys.stream(), values.stream(), (k, v) -> new AbstractMap.SimpleImmutableEntry(k, v))
                        .collect(ImmutableListMultimap::builder,
                                ImmutableListMultimap.Builder::put,
                                (builder2, builder3) -> builder2.putAll(builder3.build())

                        ).build();

: - builder2.putAll(builder3.build()) BiConsumer . collect ( ).

+2

Source: https://habr.com/ru/post/1694822/


All Articles