Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split a list stream into a map does need a custom Collector?

am new to Stream but not so much... this is my problem:

I have a list that am reading from pc where I have users with some kind of rights over an exe file... the list I got as a 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 a Map<String, String> like

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

but my code is producing:

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

I know i can edit the set of values if i decide to keep working with that result but am looking a more elegant way of get that in a only one stream instruction and I have the feeling I will need a custom collector for that...

my try so far..

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

System.out.println(result);

any suggestion?

like image 375
FlascheLeer Avatar asked Dec 08 '22 16:12

FlascheLeer


1 Answers

Something like this (you were really close btw):

xyzList.stream()
       .map(x -> x.split("\\."))
       .collect(
            Collectors.groupingBy(arr -> arr[0],
            Collectors.mapping(
                         arr -> arr[1], 
                         Collectors.joining("-"))))
like image 135
Eugene Avatar answered Mar 15 '23 17:03

Eugene