簡體   English   中英

如何從列表創建ConcurrentHashMap <Student> [等候接聽]

[英]How to create ConcurrentHashMap from List<Student> [on hold]

我有一個Student對象List ,需要使用Java 8創建ConcurrentHashMap<String, List>

輸入-> List<Student>輸出-> ConcurrentHashMap<String,List<Student>>

從您的問題尚不清楚,地圖值List將包含哪些內容,但假設它類似於學生姓名列表。

您可以使用Collectors.toConcurrentMap()

import java.util.stream.Collectors;

然后是這樣的:

studentList.stream().collect(
    Collectors.toConcurrentMap(Student::getId, Student::getNames));

這是完整的代碼示例:

public static class Student {
    private final String id;
    private final List<String> names;

    public Student(String id, String...names) {
        this.id = id;
        this.names = Arrays.asList(names);
    }

    public String getId() {
        return id;
    }

    public List<String> getNames() {
        return names;
    }
}

public static void main(String[] args) throws Exception {
    List<Student> studentList = new ArrayList<>();
    studentList.add(new Student("fred", "Fred", "Bloggs"));
    studentList.add(new Student("bob", "Bob", "Bobbins"));

    ConcurrentMap<String, List<String>> map = studentList.stream().collect(
            Collectors.toConcurrentMap(Student::getId, Student::getNames));

    System.out.println(map.get("bob").get(1));
}

印刷品:

線軸

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM