簡體   English   中英

過濾對象列表中的 object 列表

[英]Filtering list of object inside list of objects

所以我有一個對象列表:

        List<GpbCodesAndVersions> lst = Arrays.asList(new GpbCodesAndVersions("code1", 1, Arrays.asList(new General(1), new General(2))),
            new GpbCodesAndVersions("code2", 2,  Arrays.asList(new General(1), new General(5))),
            new GpbCodesAndVersions("code3", 3,  Arrays.asList(new General(2), new General(3))),
            new GpbCodesAndVersions("code4", 4,  Arrays.asList(new General(2), new General(4))));

我想過濾此列表並獲取僅包含 General(1) 字段的列表: GpbCodesAndVersions(code=code1, version=1, content=[General(status=1)]), GpbCodesAndVersions(code=code2, version=2, content=[General(status=1)])

我的代碼正在運行,但也許可以做得更漂亮? 我的代碼:

    List<GpbCodesAndVersions> versionOneGeneral = lst.stream().peek(x -> {
        List<General> generals = x.getContent().stream().filter(y -> y.getStatus().equals(1)).toList();
        x.setContent(generals);
    }).filter(z -> !z.getContent().isEmpty()).toList();

通常不建議對此類任務使用peek ,因為它會強制您使用副作用來就地修改列表。

最好使用無副作用的map創建新版本的列表(函數式):

final List<GpbCodesAndVersions> list = Arrays.asList(
        new GpbCodesAndVersions("code1", 1, Arrays.asList(new General(1), new General(2))),
        new GpbCodesAndVersions("code2", 2,  Arrays.asList(new General(1), new General(5))),
        new GpbCodesAndVersions("code3", 3,  Arrays.asList(new General(2), new General(3))),
        new GpbCodesAndVersions("code4", 4,  Arrays.asList(new General(2), new General(4))));

final List<GpbCodesAndVersions> newList = list.stream()
    .map(x -> new GpbCodesAndVersions(
            x.getCode(),
            x.getId(),
            x.getContent().stream().filter(g -> g.getStatus() == 1).toList()))
    .filter(Predicate.not(x -> x.getContent().isEmpty()))
    .toList();

這將使原始列表中的所有 GpbCodesAndVersions 保持不變,並創建一個包含新 GpbCodesAndVersions 和新將軍列表的新列表。 兩個列表現在是獨立的,一個列表的修改不會影響另一個列表(這避免了未縮進的修改)。

我認為 anyMatch 可以提供幫助

List<GpbCodesAndVersions> result = list.stream()
        .filter(x -> x.getContent().stream().anyMatch(y -> y.getStatus() == 1))
        .collect(Collectors.toList());

System.out.println("result = " + result);

//result = [GpbCodesAndVersions{code='code1', id=1, content=[General{status=1}, General{status=2}]}, GpbCodesAndVersions{code='code2', id=2, content=[General{status=1}, General{status=5}]}]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM