Search code examples
java-8collectors

How to build a HashMap<String, Set<String>> using java8 collectors


I am trying to learn java8 and specifically collectors for building collections. I have a pre-java8 way for building a particular HashMap<String, Set> . It is the following:

HashMap<String, Set<String>> setHashMap = new HashMap<>();
Set<String> set = Sets.newHashSet("1000", "1001");
setHashMap.put("Id01",set);

I am trying unsuccessfully to build the same structure with java8 as follows:

String[] IDS = {"1000", "1001"};
Sets.newHashSet("Id01", Arrays.stream(IDS).collect(toMap()));

However, this does not even compile. I would be grateful for any insights. Thanks


Solution

  • Mr Shaikh provided me with a nice solution, but it required Java9, and I wanted a solution using Java8. Mr Holger gave me a Java8 solution. That is what I am posting here as a solution. However, he pointed out to me that this is not an ideal solution for tiny amounts of static data (which is what my use case is). However, as I mentioned in my original post, this was a learning exercise for me to use Java 8 with collectors. So the below solution satisfies my original intent (even though not particularly efficient for my use case):

    Map<String, Set<String>> setMap = Stream.of("1000", "1001") .collect(Collectors.groupingBy(e -> "Id01", Collectors.toSet()));