2017-04-10 9 views
2

ストリームを使用して、型Bから型Aのコレクションを作成します。Java 8ストリームA型のコレクションから型Bのコレクションを作成します。

私はコード

現在
public static List<Person> createPersonsFromEmployees(List<Employee> employees) { 

     List<Person> persons = new ArrayList<>(); 

     employees.stream().filter(Object :: nonNull) 
        .forEach(e -> { 
         persons.add(new Person(e.getFirstName(), 
              e.getLastName(), 
              e.getEmail()); 
        };) 


     return persons; 
} 

、コードの作品のこの部分以下の書いてきました、私は従業員のコレクションから人のコレクションを作成するには、二つのクラス

Class Employee{ 
    String firstName; 
    String lastName; 
    int age; 
    String id; 
    String email; 
    double salary; 
} 

Class Person { 
    String firstName; 
    String lastName; 
    String email; 
} 

があるとします。しかし、forEachを使わずにEmployeeからPersonのコレクションを作成するより良い方法があるのか​​どうか疑問に思っています。

答えて

2

ので、私はそれをスキップします。マッピング方法は、次にcollect(mapping(...))はO(N)であるので、方法を収集するが、map(...).collect(...)がO(2N)であるが、collect(mapping(...))よりmap(...).collect(...)読みやすく、かつmapping代わりFunction<Employee,Person>の公開transform(Employee)方法基準を参照してマップよりも高速であること

ノートEmployeePersonに変換する方法として再利用されます。 2つの方法は同じセマンティクスを持っており、両方ともadapterメソッドです。

public List<Person> transform(List<Employee> employees) throws Throwable { 
    return employees.stream() 
      .filter(Objects::nonNull) 
      .collect(Collectors.mapping(this::transform, Collectors.toList())); 
} 

public Person transform(Employee it) { 
    return new Person(it.firstName, it.lastName, it.email); 
} 
+0

多くの説明をありがとう。 – cmodha

3

アダプタクラスを作成します。その後、

class EmployeeToPersonAdapter { 

    private EmployeeToPersonAdapter() { 
    } 

    public static Person toPerson(Employee employee) { 
     if (employee == null) { 
      return null; 
     } 
     return new Person(employee.getFirstName(), 
       employee.getLastName(), 
       employee.getEmail()); 
    } 
} 

そして、それを使用します。

public static List<Person> createPersonsFromEmployees(List<Employee> employees) { 
    return employees.stream() 
      .filter(Objects::nonNull) 
      .map(EmployeeToPersonAdapter::toPerson) 
      .collect(Collectors.toList()); 
} 
+0

時間を節約し、解決策を共有していただきありがとうございます。 – cmodha

7

は、ここでそれをやって少しクリーナー方法です。ストリームでの.forEach()の使用は、おそらくストリームを使用するより良い方法があることを示す記号です。ストリームは機能的であることが意図されており、変更可能性から離れようとします。あなたは他の人がすでに提供しているCollectors.mapping/Stream.mapを使用することができますEmployeePersonへのマッピング

public static List<Person> createPersonsFromEmployees(List<Employee> employees) 
    Function<Employee, Person> employeeToPerson = e -> new Person(e.getFirstName, e.getLaseName(), e.getEmail()); 

    return employees.stream() 
        .filter(Object :: nonNull) 
        .map(employeeToPerson) 
        .collect(Collectors.toList()); 

} 
+1

私はこの解決策に同意します。私が変更する唯一の方法は、よりスマートな方法でコンストラクタのフィールドを処理するためにPersonクラスのBuilderを作成することです。 –

+0

あなたの考えとあなたの意見を共有してくれてありがとう、それをより良くする方法をありがとう。 – cmodha

関連する問題