Created
July 27, 2019 08:05
-
-
Save will-molloy/2fe55933707d3028e538e8a12218dbab to your computer and use it in GitHub Desktop.
Grouping By alternative (Guava Multimaps)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.common.collect.ImmutableSetMultimap; | |
import com.google.common.collect.Multimap; | |
import java.util.List; | |
import java.util.Map; | |
import java.util.function.Function; | |
import java.util.stream.Collectors; | |
class GroupingByAlternative { | |
public static void main(String... args) { | |
var list = List.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); | |
Multimap<Boolean, Integer> guava = list.stream() | |
.collect(ImmutableSetMultimap.toImmutableSetMultimap(i -> i % 2 == 0, Function.identity())); | |
Map<Boolean, List<Integer>> javaCollectors = list.stream() | |
.collect(Collectors.groupingBy(i -> i % 2 == 0)); | |
System.out.println(guava); // {true=[0, 2, 4, 6, 8], false=[1, 3, 5, 7, 9]} | |
System.out.println(javaCollectors); // {false=[1, 3, 5, 7, 9], true=[0, 2, 4, 6, 8]} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment