英文:
Return 1st object from the array matching any value from input array using Java 8
问题
我有一个值列表 1,2,3,4
。如何对这些值进行结构化取决于我,可以是 Array
、ArrayList
等等。
接下来,我有来自 REST 调用的响应,该响应可能包含或不包含这些值。我的目标是从响应的 field4
中返回第一个包含这些值的对象。响应的结构如下所示。在这种情况下,我希望返回数组中的第二个对象,因为 4 是与给定输入的第一个匹配项。
{
"field1": "",
"field2": "null",
"responseArray": [
{
"field3": "abc",
"field4": "8",
"field5": "def"
},
{
"field3": "abc",
"field4": "4",
"field5": "def"
},
{
"field3": "abc",
"field4": "1",
"field5": "def"
}
]
}
我理解我可以采用蛮力方法,遍历响应的每个对象,然后将 field4
与给定输入值进行匹配,一旦找到匹配项,就退出循环,以跳过遍历剩余的对象。但是,是否有其他更有效的方法,特别是使用 Java8 的功能?
英文:
I have a list of values 1,2,3,4
. It depends on my how I want to struct these values, be it Array
, ArrayList
, etc.
Then, I have the response coming from rest call which may or may not contain these values. My object is to return 1st object from the response's field4 which contains these values. The structure of response will be like below. In this case, I would like to return 2nd object from the array since 4 is the 1st match with given input.
{
"field1": "",
"field2": "null",
"responseArray": [
{
"field3": "abc",
"field4": "8",
"field5": "def"
},
{
"field3": "abc",
"field4": "4",
"field5": "def"
},
{
"field3": "abc",
"field4": "1",
"field5": "def"
}
]
}
I understand I can do brute-force method where I can traverse through each object of the response, then match field4 with given input values and once match is found, exit the loop so as to skip traversing rest of the loop. But, is there another effective way that can be used here specially with features from java8?
答案1
得分: 0
如果您对值使用Set,那么像这样的代码将起作用:
(假设responseArray是一个具有getField4方法的对象数组)
Arrays.stream(responseArray).findFirst(e -> values.contains(e.getField4()));
英文:
If you use a Set for your values, then something like this would work:
(assuming your responseArray is an array of objects that has a getField4 method)
Arrays.stream(responseArray).findFirst(e -> values.contains(e.getField4()));
专注分享java语言的经验与见解,让所有开发者获益!
评论