1

Given this class written in the Java 8 style, I wanted to see if I dont need to call the stream api twice :

import java.util.*;

public class Foo {

public static void main(String... args) {
    List<Person> persons = new ArrayList<>();
    init(persons, Person::new, "John", "Doe");


    persons.stream()
           .map(Person::getFirstName)
           .forEach(System.out::println);

    persons.stream()
           .map(Person::getLastName)
           .forEach(System.out::println);
}

@FunctionalInterface
interface PersonFactory {
    Person create(String firstName, String lastName);
}

private static void init(List<Person> persons, PersonFactory factory, String fn, String ln) {
    persons.add(factory.create(fn, ln));
}

}

class Person {
    private final String firstName;
    private final String lastName;

    public Person(String fName, String lName) {
        this.firstName = fName;
        this.lastName = lName;
    }

    public String getFirstName() {return this.firstName;}
    public String getLastName() {return this.lastName;}
}

I wanted to see if I could instead stream the "persons" List in one go.

Any suggestions ?

ZeroGraviti
  • 1,047
  • 2
  • 12
  • 28
  • 3
    I don't understand your use case. If you need to traverse all the elements of the list, just use `List.forEach`, you don't even need a stream. A stream is useful when you need to i.e. filter some elements of the list or apply some transformation to the elements of the list, i.e. transform each person whose name starts with `A` into a `Frog` and then collect them into a separate list. – fps May 29 '17 at 15:44

2 Answers2

2

If you don't need to transform object to another, you can try this

persons.forEach(i -> System.out.println(i.getFirstName() + " " + i.getLastName()));
ing8ar
  • 119
  • 1
  • 5
0

i think it could be helpfull for you using Map

Map<String, String> mapp = persons.stream().collect(HashMap::new,
  (m, c) ->{
           m.put(c.getFirstname(), "");
           m.put(c.getLastname(), "");
  },HashMap::putAll);

System.out.println(mapp.keySet().toString());
Kalaiselvan
  • 2,095
  • 1
  • 18
  • 31