簡體   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