Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA8 - Grouping with lambda

Tags:

java

lambda

I have a collection with structure like this:

@Entity
public class RRR{

    private Map<XClas, YClas> xySets;

}

and XClas has a field called ZZZ

my question is: I would like to aggregate it with lambda to get a Map<ZZZ, List<RRR>>.

Is it possible? Now I'm stuck with:

Map xxx = rrrList.stream().collect(
                Collectors.groupingBy(x->x.xySets().entrySet().stream().collect(
                        Collectors.groupingBy(y->y.getKey().getZZZ()))));

but it's Map<Map<ZZZ, List<XClas>>, List<RRR>> so it's not what I was looking for :)

Right now just to make it work, I did aggregation with two nested loops, but it would be so great, if you could help me make it done with lambdas.

EDIT

I post what I got by now, as asked. I already left nested loops, and I manage to work my way up to this point:

Map<ZZZ, List<RRR>> temp;
rrrList.stream().forEach(x -> x.getxySetsAsList().stream().forEach(z -> {
            if (temp.containsKey(z.getKey().getZZZ())){
                List<RRR> uuu = new LinkedList<>(temp.get(z.getKey().getZZZ()));
                uuu.add(x);
                temp.put(z.getKey().getZZZ(), uuu);
            } else {
                temp.put(z.getKey().getZZZ(), Collections.singletonList(x));
            }
        }));

Thanks in advance

like image 915
Lukas Novicky Avatar asked Dec 25 '22 05:12

Lukas Novicky


1 Answers

Something like that? :

    Map<ZZZ, List<RRR>> map = new HashMap<>();

    list.stream().forEach(rrr -> {
        rrr.xySets.keySet().stream().forEach(xclas -> {
            if (!map.containsKey(xclas.zzz))
                map.put(xclas.zzz, new ArrayList<RRR>());
            map.get(xclas.zzz).add(rrr);
        });
    });
like image 143
korda Avatar answered Dec 28 '22 05:12

korda