2016-11-17 3 views
0
class Student { 
    int studentId; 
    String studentName; 
    String studentDept; 
    public Student() {} 
} 

私はこれらの学生のオブジェクトのリストを持って、java8のストリームマップを使用してクラスオブジェクトのリストからハッシュマップまたはハッシュテーブルを生成する方法は?

List<Student> studentList; 

私はこれらの学生のリストオブジェクトから、ハッシュマップを生成します。

HashMap<Integer,String> studentHash; 

ハッシュマップには、sudentidと名前リストのキー値のペアが含まれています。

+0

がどうあるべきかマップキーと値? – Saravana

+4

何を試しましたか?これはコード作成サービスではありません。ヒントは次のとおりです: 'Collectors'の' toMap'メソッドを見てください。 – marstran

答えて

2

あなたは明らかにMap特定の実装を必要として、あなたはmapSupplier代わりのtoMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper)も、シーンの背後にある場合、それはまだなるために提供できるようにする方法Collectors.toMapを使用する必要がありますHashMapを返します。javadocには明示的に指定されていないため、次のバージョンのJavaでそれが本当であるかどうかを確認する方法がありません。

だからあなたのコードは次のようなものでなければなりません:あなたは、単に次のようコレクターとしてtoMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper)を使用し、Mapの実装を気にしない場合は

HashMap<Integer,String> studentHash = studentList.stream().collect(
    Collectors.toMap(
     s -> s.studentId, s -> s.studentName, 
     (u, v) -> { 
      throw new IllegalStateException(
       String.format("Cannot have 2 values (%s, %s) for the same key", u, v) 
      ); 
     }, HashMap::new 
    ) 
); 

Map<Integer,String> studentHash = studentList.stream().collect(
    Collectors.toMap(s -> s.studentId, s -> s.studentName) 
); 
3

このような何か:

studentList.stream().collect(
    Collectors.toMap(Student::getStudentId, Student::getStudentName) 
) 
関連する問題