Java 8 - limiting stream of first object and convert to specific object?

Learn Hadoop :

Earlier I use:

List<Person> person = UserDB.getUserDetails();
Person p = person.get(0); // index of first position 
System.out.println(p.getFirstName()); // sometime i am getting 
                                      // NULL pointer issue if person object is null

in Java 8, I tried with map(Person::new). it is causing the issue.

person.stream().limit(1).map(Person::new).

How can I implement?

Nikolas :

You can do the following:

person.stream()                                              // stream
      .findFirst()                                           // finds the first
      .ifPresent(i -> System.out.println(i.getFirstName())); // if present, print the name

If you want to work with the Person in case the List<Person> is empty, use Optional:

Optional<Person> p = person.stream().findFirst();
p.ifPresent(i -> System.out.println(i.getFirstName()));

This solution assumes the list has elements or not (is empty). However if null occurs in the List<Person>, you have to filter the null values out first:

Optional<Person> p = person.stream().filter(Objects::nonNull).findFirst();
p.ifPresent(i -> System.out.println(i.getFirstName()));

Finally, if you wish to work with a Person on the specific index, use skip and limit. Don't forget to filter the List<Person> after skip-limit` or else the index will not match:

// person.get(3)
Optional<Person> p = person.stream().skip(3).limit(1).filter(Objects::nonNull).findFirst();
p.ifPresent(i -> System.out.println(i.getName()));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=84924&siteId=1