Best way to use stream with class and subclass

2020-07-24 06:38发布

I have a problem to use streams in java 8, I have 3 class like this:

public Class A {
    String string1A;
    String string2A;
    List<B> listB;
    .
    .
    .
}
public Class B {
    String string1B;
    String string2B;
    .
    .
    .
}
public Class C {
    String string1A;
    String string2A;
    String string1B;
    String string2B;
    .
    .
    .
}

Then I have a method that returns a List of C with all the data coming from a database, and I need to create a List A that has all the data grouped, the grouping value is the String1A. My idea was this:

List<A> listA = new ArrayList<A>();

    Set<String> listString1A = listC.stream().map(x->x.getString1A()).distinct().collect(Collectors.toSet());

for(String stringFilter1A: listString1A){
    A a = listC.stream()
               .filter(x->getString1A().equals(stringFilter1A))
               .map(x-> new A(x.getString1A(),x.getString2A))
               .findFirst().get();
    List<B> listB = listC.stream()
                         .filter(x->getString1A().equals(stringFilter1A))
                         .map(x-> new B(...))
                         .collect(Collectors.toList());
    a.setListB(listaB);
    listaA.add(a);
}

Is there a way to make such a query using only streams or trying to delete the for?

Thanks.

1条回答
我欲成王,谁敢阻挡
2楼-- · 2020-07-24 07:04

Here's a way that groups c elements by A, mapping each C to a new B:

Map<A, List<B>> map = listC.stream()
    .collect(Collectors.groupingBy(
        c -> new A(...),     // construct new A instance out from c instance
        Collectors.mapping(
            c -> new B(...), // construct new B instance out from c instance
            Collectors.toList())));

This requires class A to implement hashCode and equals consistently, based on string1A.

Then, you simply set the List<B> for each A in the map:

map.forEach((a, listB) -> a.setListB(listB));

And the keys of your map are what you want:

Set<A> setA = map.keySet();

Or if you really need a list:

List<A> listA = new ArrayList<>(map.keySet());
查看更多
登录 后发表回答