Java Stream, Need to update list of list objects

67 Views Asked by At

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());
1

There are 1 best solutions below

2
ODDminus1 On BEST ANSWER

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 -> "1".equals(i.getId()))
  .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.