Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ImmutableMap collector for Stream of Map.Entry #3781

Open
will-molloy opened this issue Jan 23, 2020 · 3 comments · May be fixed by #3897
Open

ImmutableMap collector for Stream of Map.Entry #3781

will-molloy opened this issue Jan 23, 2020 · 3 comments · May be fixed by #3897

Comments

@will-molloy
Copy link
Contributor

Noticed a lot of code looks like this:

    ImmutableMap<Integer, String> map = Stream.of(1, 2, 3, 4, 5)
        .map(i -> Maps.immutableEntry(i, String.valueOf(i)))
        .collect(toImmutableMap(Map.Entry::getKey, Map.Entry::getValue));

Would be nice if there was a collector for collecting Stream<Map.Entry<K, V>> into ImmutableMap<K, V> so the above can look like:

    ImmutableMap<Integer, String> map = Stream.of(1, 2, 3, 4, 5)
        .map(i -> Maps.immutableEntry(i, String.valueOf(i)))
        .collect(toImmutableMap());

The collector can be implemented like:

  static <K, V> Collector<Map.Entry<K, V>, ?, ImmutableMap<K, V>> toImmutableMap() {
    return ImmutableMap.toImmutableMap(Map.Entry::getKey, Map.Entry::getValue);
  }
@perceptron8
Copy link
Contributor

Isn't

ImmutableMap<Integer, String> map = Stream.of(1, 2, 3, 4, 5)
	.collect(toImmutableMap(i -> i, String::valueOf));

even nicer? ;)

@perceptron8
Copy link
Contributor

Also, this issue seems to be related to #2632.

@will-molloy
Copy link
Contributor Author

Lol sorry my example wasn't very good.

Usually the Stream<Map.Entry> is created from entrySet().stream().

Also have seen it with flatmap. E.g.

    ImmutableMap<String, Integer> map =
        Stream.of(1, 2, 3)
            .flatMap(i -> Stream.of("A", "B", "C").map(s -> Maps.immutableEntry(s + i, i)))
            .collect(toImmutableMap(Map.Entry::getKey, Map.Entry::getValue));

Have also seen streams of Table.Cell with

.collect(toImmutableTable(Table.Cell::getRowKey, Table.Cell::getColumnKey, Table.Cell::getValue));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants