Test.java
private String Names;
private List<InnerList> innerlist = new ArrayList<InnerList>();
InnertList.java
private String id;
private Long x;
private Long y;
[class Test {
Name: test
innerlist: [class Innerlist{
id: 1
x: 0
y: 0
}]
}]
I have following list:
List\<Test\> list = new ArrayList\<Test\>();
Now, I need to update x or y based on two conditions: if Name matches to "Test" & id matches to 1.
I tried writing, but I’m not sure how to update the x/y using setter. I need filter it twice but not sure how to put a condition when getInnerList because the condition is on the variable of inner list.
list.stream().filter(u-\>u.getName().equals("Test")).filter(t1-\>t1.getInnerList());
>Solution :
The part .filter(t1->t1.getInnerList()) doesn’t really make sense, since .filter(...) expects a predicate as the argument, i.e. a lambda with boolean as the return value. I’m not 100% sure about what you want to achieve, but I assume this would solve your case:
list.stream()
.filter(u -> "Test".equals(u.getName()))
.flatMap(u -> u.getInnerList().stream())
.filter(i -> i.getId() == 1)
.forEach(i -> {
// write your setters on `i` here
}
)
Using Stream::flatMap here, we obtain a stream of the elements of innerList for the list elements which satisfies the previous filter.