簡體   English   中英

Java 8-如何將Pojo轉換為其嵌入式Pojo屬性的列表

[英]Java 8 - How convert Pojo into list of its embedded Pojo property

我有一個數據庫調用,如果不符合任何條件,則可能返回null。 如果存在記錄匹配,則結果為Pojo,其中包含嵌入對象的列表。 我想將該Pojo轉換為其嵌入式對象ID的列表。

Foo.class有酒吧列表

public class Foo {
    private List<Bar> bars;
    //..setters & getters
}

Bar.class,我想將Foo轉換為Bar的ID列表

public class Bar {
    Integer id
    //..setters & getters
}

我厭倦了使用Optional,但是它總是返回到酒吧列表

Optional.ofNullable(fooRepo.search("some foo"))
    .map(foo -> foo.getBars()); //How can turn this into list of Bar's Id 

我不確定我是否理解您的問題,但我將其解釋為:

數據庫查詢可以返回一個對象,該對象包含對另一個對象的引用列表,如果沒有返回引用,則返回null。 如何將該對象(或null)轉換為引用對象的值列表。 如果查詢返回空值,我想要一個空列表。

如果您的問題正確無誤,那么我建議:

Optional<Foo> possibleFoo = Optional.ofNullable(dbQuery());
List<Integer> ids = possibleFoo
    .map(f -> f.bars.stream()
        .map(b -> b.id)
        .collect(Collectors.toList()))
    .orElse(Collections.EMPTY_LIST);

干得好:

Optional.ofNullable(foo).map(Foo::getBars).map(y -> y.stream().map(z -> z.id).collect(Collectors.toList()))

完整的測試代碼:

public class Test {
    public static class Bar {
        public Bar(Integer id) {
            this.id = id;
        }

        Integer id;
    }

    public static class Foo {
        private List<Bar> bars = new ArrayList<>();

        public List<Bar> getBars() {
            return bars;
        }
    }

    public static void main(String[] argb) {
        Foo nullFoo = null;
        Optional<List<Integer>> nullList = convertToIdList(nullFoo);
        System.out.println(nullList); // Optional.empty

        Foo notNullFoo = new Foo();
        notNullFoo.getBars().add(new Bar(3));
        notNullFoo.getBars().add(new Bar(4));
        notNullFoo.getBars().add(new Bar(5));
        Optional<List<Integer>> notNullList = convertToIdList(notNullFoo);
        System.out.println(notNullList); // Optional[[3, 4, 5]]
    }

    private static Optional<List<Integer>> convertToIdList(Foo foo) {
        return Optional.ofNullable(foo).map(Foo::getBars).map(y -> y.stream().map(z -> z.id).collect(Collectors.toList()));
    }
}

關鍵是將列表本身視為Optional,但是如果存在的話,則將單個列表從一種元素類型轉換為另一種元素類型。 請讓我知道,如果你有任何問題。

暫無
暫無

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

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