Skip to content

Instantly share code, notes, and snippets.

@achukka
Created February 22, 2023 17:45
Show Gist options
  • Save achukka/ca31eb839a77736f8d93507833768c9a to your computer and use it in GitHub Desktop.
Save achukka/ca31eb839a77736f8d93507833768c9a to your computer and use it in GitHub Desktop.
Create Maps using a reduce operation
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.Arrays;
public class MyClass {
public static void main(String args[]) {
List<String> values = List.of("1", "2", "3", "4", "5", "5", "2");
Map<String, List<String>> map = values.stream()
.collect(Collectors.toMap(
v -> v,
v -> new ArrayList<>(Arrays.asList(v)),
(left, right) -> {
left.addAll(right);
return left;
}
));
System.out.println(map);
}
}
@achukka
Copy link
Author

achukka commented Feb 22, 2023

java -cp /tmp/p8nc3kSSrJ MyClass
{1=[1], 2=[2, 2], 3=[3], 4=[4], 5=[5, 5]}

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