Created
February 22, 2023 17:45
-
-
Save achukka/ca31eb839a77736f8d93507833768c9a to your computer and use it in GitHub Desktop.
Create Maps using a reduce operation
This file contains 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 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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
java -cp /tmp/p8nc3kSSrJ MyClass
{1=[1], 2=[2, 2], 3=[3], 4=[4], 5=[5, 5]}