java – 使用流将集合简化为另一种类型的单个对象
发布时间:2020-12-15 04:49:41 所属栏目:Java 来源:网络整理
导读:我找不到使用 Java流将一种类型(例如MyData)的集合减少到另一种类型的对象(例如MyResult)的解决方案. @Testpublic void streams() { ListMyData collection = Arrays.asList( new MyData("1","cool"),new MyData("2","green"),new MyData("3","night")); //
我找不到使用
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); } } 是否有使用某种减少或折叠的解决方案? 解决方法
你的意思是 :
collection.stream() .filter(e -> e.key.equals("2")) .findFirst() .orElse(null);//Or any default value 你甚至可以抛出异常: collection.stream() .filter(e -> e.key.equals("2")) .findFirst() .orElseThrow(() -> new IllegalArgumentException("No data found")); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |