Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java Stream, Need to update list of list objects

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading