Java 如何从地图对象获取列表值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24255964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:06:37  来源:igfitidea点击:

How to get List value from map object

javalisthashmap

提问by Miss_Ann

I have object value called "mastervalue" from my hashmap. The mastervalue contain ques_id as key, and an array contain score and answer as value. How to get value of the array only(the score and answer) and return as List.

我的哈希图中有一个名为“mastervalue”的对象值。mastervalue 包含 ques_id 作为键,数组包含 score 和 answer 作为值。如何仅获取数组的值(分数和答案)并作为列表返回。

String maprule = "department == '2' && topic == '1'";

mastervalue = (Map<String, List<String>>) map_master.get(maprule);
System.out.println(mastervalue);

mastervalue print out : {10359=[4, 1], 10365=[1, 1], 10364=[1, 1], 10363=[4, 1], 10362=[3, 1], 10369=[1, 1], 10368=[5, 1]}

主值打印输出:{10359=[4, 1], 10365=[1, 1], 10364=[1, 1], 10363=[4, 1], 10362=[3, 1], 10369=[1, 1], 10368=[5, 1]}

采纳答案by Rogue

Okay:

好的:

public <T> List<T> getValues(Map<?, T> map) {
    return new ArrayList<>(map.values());
}

Inlined:

内联:

List<List<String>> list = new ArrayList<>(map_master.values());

Or using the method:

或者使用以下方法:

List<List<String>> list = getValues(map_master);

Alternatively, if you want to put all the values of all the lists into one, just iterate:

或者,如果您想将所有列表的所有值合二为一,只需迭代:

List<String> total = new ArrayList<>();
for (List<String> lis : map_master.values()) {
    total.addAll(lis);
}

And with Java 8 streams:

使用 Java 8 流:

List<String> total = map_master.values().stream()
                            .flatMap(Collection::stream)
                            .collect(Collectors.toList());