与类和子类一起使用流的最佳方法 [英] Best way to use stream with class and subclass

查看:79
本文介绍了与类和子类一起使用流的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java 8中使用流时遇到问题,我有3个这样的类:

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;
    .
    .
    .
}

然后,我有一个方法返回一个C列表,其中所有数据都来自数据库,我需要创建一个将所有数据分组的列表A,分组值为String1A .我的想法是这样的:

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);
}

是否有一种仅使用流或试图删除for进行查询的方法?

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

谢谢.

推荐答案

这是将c元素按A分组的一种方式,将每个C映射到新的B:

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())));

这需要类A基于string1A一致地实现hashCodeequals .

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

然后,您只需为地图中的每个A设置List<B>:

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

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

地图键就是您想要的:

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

或者如果您确实需要列表:

Or if you really need a list:

List<A> listA = new ArrayList<>(map.keySet());

这篇关于与类和子类一起使用流的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆