繁体   English   中英

如何通过使用带有过滤器的另一个列表对象值来使用 java 8 流创建新列表?

[英]How to use java 8 streams to make a new list by using another's list objects values with filter?

我有以下几点:

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

class BBB {
  String A3;
  String A4;
}


List<AAA> aaaList= new ArrayList<>(); // has 10 objects

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

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

但不知道这应该如何工作......

假设这些类具有适当的 getter、setter。 构造函数按顺序接受参数。

所以这:

List<AAA> listAAA =
        new ArrayList<>(List.of(new AAA("1", "2", "3", "4"),
                new AAA("1", "1", "30", "40"),
                new AAA("5", "6", "3", "4"),
                new AAA("1", "2", "3", "4"),
                new AAA("4", "4", "50", "60")));
List<BBB> listBBB = listAAA.stream()
        .filter(ob -> ob.getA1().equals(ob.getA2()))
        .map(ob -> new BBB(ob.getA3(), ob.getA4()))
        .collect(Collectors.toList());
System.out.println(listBBB);

会打印这个:

[BBB [A3=30, A4=40], BBB [A3=50, A4=60]]

这是代码,注释中有解释。

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'}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM