2

I'm fairly new to Java8. I have a requirement to convert List of POJOs to group by a certain criteria and show it on UI.

  • Convert list of objects that belong to Children category to Person category.
  • Return the List.

    Children.java
    private String firstName;
    private String lastName;
    private String school;
    private String personId;
    // Setters and getters.
    
    Person.java
    private String fullName;
    private String address;
    // Setters and Getters.
    
    private Person convertChildToPerson(Children child) {
             Person person = new Person();
             person.setFullName(child.getLastName() + ", " + child.getFirstName());
              ..
              return person;
     } 
    

    .. MAIN CODE.. ..

    List<Person> personList;  // Is populated by other functions.
    
    // Connect to DB and gets the output
    List<Children> childrenList = (Children) criteria.list();  
    
    for(Children children: childrenList) {
         personList.add(convertChildToPerson(children));
    }
    return personList; 
    

    Can't the FOR-LOOP present above be replaced by Java 8 Streams?

1
  • See the answer from Robert Bräutigam Commented Feb 27, 2018 at 19:14

1 Answer 1

4
 List<Person> newList = childrenList.stream()
             .map(this::convertChildToPerson)
             .collect(Collectors.toList());

 personList.addAll(newList);

Even shorter (and nicer), as suggested by Holger:

childrenList.stream()
            .map(this::convertChildToPerson)
            .forEachOrdered(personList::add);
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the reply Eugene. But I already have personList which has been populated by other methods. I can't override that... So, should I have to do personList1 = ..... and then personList.addAll(personList1) ?
@SrinivasLakshman right, see edit
forEachOrdered(personList::add) would work too. Collecting into a new list before adding them at once may look cleaner, but implies needing temporary storage.
@Holger good suggestion, thx

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.