Java 9 Optional :: stream

There are Company and Employee classes as shown below, and there are many Employees in Company.

Employee.java


public class Employee {
  private String id;
  private String name;
}

Company.java


public class Company {
  private List<Employee> employees = new ArrayList<>();
  
  public Option<Employee> getEmployeeById(String employeeId) {
    return employees.stream().filter(e -> e.id.equals(employeeId)).findFirst()
  }

  public List<Employee> getEmployeeList(List<String> employeeIds) {
  }
}

Next, I want to get the list of ʻEmployee in the list of ʻemployeeIds, I want to implement getEmployeeList, I will implement Java8 and Java9.

Java8.java


public List<Employee> getEmployeeList(Collection<String> employeeIds) {
  return employeeIds.stream()
    .map(this::getEmployeeById)
    .filter(Optional::isPresent)
    .map(Optional::get)
    .collect(toList());
}

Java9.java


public List<Employee> getEmployeeList(Collection<String> employeeIds) {
  return employeeIds.stream()
    .map(this::getEmployeeById)
    .flatMap(Optional::stream)
    .collect(toList());
}

Java 9's ʻOptional :: stream makes the code for getEmployeeList` shorter.

Recommended Posts

Java 9 Optional :: stream
[JAVA] Stream type
Try Java 8 Stream
Java Optional type
Studying Java 8 (Optional)
Java Stream API
Studying Java 8 (Stream)
Java Stream termination
[Java] Stream processing
[Java] Optional memorandum
[Java] Stream Collectors notes
[Java] Stream API-Stream generation
[Java] Stream API / map
View Java Optional Javadoc
Java8 Stream reduction operation
Java8 Stream Rough Summary
Rewrite Java try-catch with Optional
[Java11] Stream Summary -Advantages of Stream-
How to use java Optional
Java Stream API cheat sheet
Java
Java Stream cannot be reused.
[Java] Introduction to Stream API
Use Redis Stream in Java
Java8 to start now ~ Optional ~
[Java] How to use Optional ①
Compare Java 8 Optional with Swift
Java application for beginners: stream
How to handle exceptions coolly with Java 8 Stream or Optional
Get a non-empty collection from an Optional stream in java
[Java 8] Duplicate deletion (& duplicate check) with Stream
[java8] To understand the Stream API
About Lambda, Stream, LocalDate of Java8
[Introduction to Java] About Stream API
[Java] Element existence check with Stream
Basic usage of java Optional Part 1
I tried using Java8 Stream API
Basic processing flow of java Stream
Java 8 ~ Stream API ~ to start now
Java array / list / stream mutual conversion list
Java8 list conversion with Stream map
Do you use Stream in Java?
Java learning (0)
Studying Java ―― 3
[Java] array
[Java] Annotation
[Java] Module
Java array
Java tips, tips
Java methods
Java method
java (constructor)
Java array
[Java] ArrayDeque
Data processing using stream API from Java 8
java (override)
java (method)
Java Day 2018
java (array)
Java static
Java serialization