开发者社区> 问答> 正文

如何使用Java 8流通过使用带有过滤器的其他列表对象值来创建新列表?

我有以下几件事:

class AAA {
  String A1;
  String A2;
  String A3;
  String A4;
}

class BBB {
  String A3;
  String A4;
}
List<AAA> aaaList= new ArrayList<>(); // has 10 objects

我想用BBB对象填充第二个列表,以防A1和A2值相等。所以像这样:

List<BBB> bbbList = aaaList.stream().filter(obj -> obj.getA1().equals(obj.getA2())).map(obj -> new BBB(obj.getA3(), obj.getA4())).collect(Collectors.toList());

但是不知道这应该看起来如何工作...

问题来源:Stack Overflow

展开
收起
montos 2020-03-27 17:20:12 397 0
1 条回答
写回答
取消 提交回答
  • 这是代码,在注释中有解释。

    import java.util.List;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    //Note - Object.toString() was defined for AAA & BBB classes. Their member variables are public just to reduce code.
    public class Test {
        public static void main(String [] args){
            //Generate some test data.
            List<AAA> testData = Stream
                    .of(1,2,3,4,5)
                    .map(i -> new AAA(i+"", (i%3)+"", i*3+"", i*4+""))
                    .collect(Collectors.toList());//% is modulo operator.
    
            System.out.println("Test data:\n");
            testData.forEach(System.out::println);
    
            List<BBB> processedData = testData
                    .stream()
                    //If a.A1 = a.A2, then allow it.
                    .filter(a -> a.A1.equals(a.A2))
                    //Take an AAA and convert it into a BBB.
                    .map(a -> new BBB(a.A3, a.A4))
                    //Collect all the BBBs and put them in a list.
                    .collect(Collectors.toList());
    
            System.out.println("Processed data:\n");
            processedData.forEach(System.out::println);
        }
    }
    

    输出:

    Test data:
    
    AAA{A1='1', A2='1', A3='3', A4='4'}
    AAA{A1='2', A2='2', A3='6', A4='8'}
    AAA{A1='3', A2='0', A3='9', A4='12'}
    AAA{A1='4', A2='1', A3='12', A4='16'}
    AAA{A1='5', A2='2', A3='15', A4='20'}
    Processed data:
    
    BBB{A3='3', A4='4'}
    BBB{A3='6', A4='8'}
    

    回答来源:Stack Overflow

    2020-03-27 17:20:48
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载

相关实验场景

更多