Java 8 – restrict the flow of the first object and convert it to a specific object?

I used earlier:

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 try to use map (person:: new) It caused the problem

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

How should I implement it?

Solution

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 use person in the case of list < person > If it is empty, use optional:

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

This solution assumes that the list contains elements that are empty However, if NULL appears in list < person >, you must first filter out null values:

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

Finally, if you want to use person on a specific index, use skip and limit Don't forget to filter the list < person > after skip limit ', otherwise 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()));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>