Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we use java Stream to refactor this?

Is it possible to refactor the following for loop using Streams in Java 8?

Moving the state from the inside to outside while collecting the list for different sources?

Map<StateEnum, List<List<ThreadDo>>> stateDumpListMap = new HashMap<>();
for (ThreadDumpDo dumpDo : dumpDoList) {
    Map<StateEnum, List<ThreadDo>> stateDoListMap = getStateGroup(dumpDo);
    stateDoListMap.entrySet().stream().forEach(entry -> {
       stateDumpListMap.putIfAbsent(entry.getKey(), new ArrayList<>());
       stateDumpListMap.get(entry.getKey()).add(entry.getValue());
     });
}

Recently I tried several use cases but it just seems ugly to me.

I tried to use stream().map() to achieve that, but I failed. Can anyone please help?

like image 539
Hearen Avatar asked Oct 15 '25 04:10

Hearen


1 Answers

Here's one way, using collect instead of forEach to generate the Map, and using flatMap to eliminate the for loop:

Map<StateEnum, List<List<ThreadDo>>> stateDumpListMap =
    dumpDoList.stream ()
              .flatMap (d->getStateGroup(d).entrySet().stream ())
              .collect(Collectors.toMap (Map.Entry::getKey,
                                         e -> {
                                            List<List<ThreadDo>> l = new ArrayList<>(); 
                                            l.add (e.getValue());
                                            return l;
                                         },
                                         (v1,v2)->{v1.addAll(v2);return v1;}));

Which, as Aominè commented, can be simplified to:

Map<StateEnum, List<List<ThreadDo>>> stateDumpListMap =
    dumpDoList.stream ()
              .flatMap (d->getStateGroup(d).entrySet().stream ())
              .collect(Collectors.toMap (Map.Entry::getKey,
                                         e -> new ArrayList<>(Collections.singletonList(e.getValue())),
                                         (v1,v2)->{v1.addAll(v2);return v1;}));
like image 84
Eran Avatar answered Oct 17 '25 19:10

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!