使用流将集合缩减为另一种类型的单个对象

ssc*_*eck 3 java java-8 java-stream

我找不到使用Java流将一种类型(例如MyData)的集合减少到另一种类型的对象(例如)的解决方案MyResult.

@Test
public void streams() {
    List<MyData> collection = Arrays.asList(
            new MyData("1", "cool"), 
            new MyData("2", "green"),
            new MyData("3", "night"));

    // How reduce the collection with streams?
    MyResult result = new MyResult();
    collection.stream().forEach((e) -> {
        if (e.key.equals("2")) {
            result.color = e.value;
        }
    });

    MyResult expectedResult = new MyResult();
    expectedResult.color = "green";
    assertThat(result).isEqualTo(expectedResult);
}

public static class MyData {
    public String key;
    public String value;

    public MyData(String key, String value) {
        this.key = key;
        this.value = value;
    }
}

public static class MyResult {
    public String color;
    public String material;

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        MyResult myResult = (MyResult) o;
        return Objects.equals(this.color, myResult.color) &&
                Objects.equals(this.material, myResult.material);
    }

    @Override
    public int hashCode() {
        return Objects.hash(this.color, this.material);
    }
}
Run Code Online (Sandbox Code Playgroud)

是否有使用某种减少或折叠的解决方案?

YCF*_*F_L 10

你的意思是 :

collection.stream()
        .filter(e -> e.key.equals("2"))
        .findFirst()
        .orElse(null);//Or any default value
Run Code Online (Sandbox Code Playgroud)

你甚至可以抛出异常:

collection.stream()
        .filter(e -> e.key.equals("2"))
        .findFirst()
        .orElseThrow(() -> new IllegalArgumentException("No data found"));
Run Code Online (Sandbox Code Playgroud)