Do you need a custom collector to split the list stream into a map?

I'm new to Stream, but not so much ... this is my problem:

I have a list that reads on a PC, where I have users with some rights over the exe file ... the list that I got as String looks like

List<String> xyzList = new ArrayList<>();
xyzList.add("USER1.READ");
xyzList.add("USER1.WRITE");
xyzList.add("USER1.EXECUTE");
xyzList.add("USER1.DELETE");
xyzList.add("USER2.READ");
xyzList.add("USER3.READ");
xyzList.add("USER2.EXECUTE");

I would like to have Map<String, String>like

{USER1 = READ-WRITE-EXECUTE-DELETE, USER2 = READ-WRITE, USER3 = READ}

but my code produces:

{USER1=USER1.READ-USER1.WRITE-USER1.EXECUTE-USER1.DELETE,  USER2=USER2.READ-USER2.EXECUTE, USER3=USER3.READ}

I know that I can edit a set of values ​​if I decide to continue working with this result, but I consider a more elegant way to get this in only one stream instruction, and I feel that I need a custom collector for this ...

my attempt so far ..

Map<String, String> result = xyzList
        .stream()
        .collect(
             Collectors.groupingBy(x -> x.split("\\.")[0],  
             Collectors.joining("-", "", "")
         ));

System.out.println(result);

any suggestion?

+4
source share
1 answer

Something like this (you were very close by the way):

xyzList.stream()
       .map(x -> x.split("\\."))
       .collect(
            Collectors.groupingBy(arr -> arr[0],
            Collectors.mapping(
                         arr -> arr[1], 
                         Collectors.joining("-"))))
+14

Source: https://habr.com/ru/post/1688835/


All Articles