[英]Java stream create object and compare
I'm pretty new to Java streams. 我是Java流的新手。 I've to split a string returned by filter in stream, create a new object with the strings in the split and compare each object with a predefined object. 我要拆分流中过滤器返回的字符串,用拆分中的字符串创建一个新对象,并将每个对象与预定义对象进行比较。 Stream looks like this (I know this is incorrect, just a representation of what I am trying to do): Stream看起来像这样(我知道这是不正确的,只是我想要做的代表):
xmlstream.stream()
.filter(xml->xml.getName()) //returns a string
.map(returnedString -> split("__"))
.map(eachStringInList -> new TestObj(returnedStr[0], returnedStr[1]))
.map(eachTestObj -> eachTestObj.compareTo(givenObj))
.max(Comparing.compare(returnedObj :: aProperty))
How do I achieve this? 我该如何实现这一目标? Basically map each string in list to create an object, compare that to a fix object and return max based on one of the properties. 基本上映射列表中的每个字符串以创建对象,将其与修复对象进行比较,并根据其中一个属性返回最大值。 Thanks. 谢谢。
You could use reduce
like so: 您可以像这样使用reduce
:
TestObj predefined = ...
TestObj max =
xmlstream.stream()
.map(xml -> xml.getName()) //returns a string
.map(s -> s.split("__"))
.map(a -> new TestObj(a[0], a[1]))
.reduce(predifined, (e, a) ->
e.aProperty().compareTo(a.aProperty()) >= 0 ? e : a);
A more efficient version of the above would be: 更有效的上述版本将是:
TestObj predefined = ...
TestObj max =
xmlstream.stream()
.map(xml -> xml.getName()) //returns a string
.map(s -> s.split("__"))
.map(a -> new TestObj(a[0], a[1]))
.filter(e -> e.aProperty().compareTo(predefined.aProperty()) > 0)
.findFirst()
.orElse(predefined);
Update: 更新:
if you want to retrieve the max object by a given property from all the TestObj
objects less than the predefined TestObj
, then you can proceed as follows: 如果要从少于预定义TestObj
所有TestObj
对象中通过给定属性检索max对象,则可以按以下步骤操作:
TestObj predefined = ...
Optional<TestObj> max =
xmlstream.stream()
.map(xml -> xml.getName())
.map(s -> s.split("_"))
.map(a -> new TestObj(a[0], a[1]))
.filter(e -> e.aProperty().compareTo(predefined.aProperty()) < 0)
.max(Comparator.comparing(TestObj::aProperty));
max
returns an Optional<T>
; max
返回一个Optional<T>
; if you're unfamiliar with it then consult the documentation here to familiarise you're with the different ways to unwrap an Optional<T>
object. 如果您不熟悉它,请参阅此处的文档以熟悉打开Optional<T>
对象的不同方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.