Hashmap with Streams in Java 8 Streams 来收集 Map 的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29625529/
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
Hashmap with Streams in Java 8 Streams to collect value of Map
提问by Deepak Shajan
Let consider a hashmap
让我们考虑一个哈希图
Map<Integer, List> id1 = new HashMap<Integer,List>();
I inserted some values into both hashmap.
我在两个哈希图中插入了一些值。
For Example,
例如,
List<String> list1 = new ArrayList<String>();
list1.add("r1");
list1.add("r4");
List<String> list2 = new ArrayList<String>();
list2.add("r2");
list2.add("r5");
List<String> list3 = new ArrayList<String>();
list3.add("r3");
list3.add("r6");
id1.put(1,list1);
id1.put(2,list2);
id1.put(3,list3);
id1.put(10,list2);
id1.put(15,list3);
Q1) Now I want to apply a filter condition on the key in hashmap and retrieve the corresponding value(List).
Q1)现在我想对 hashmap 中的键应用过滤条件并检索相应的值(列表)。
Eg: Here My query is key=1, and output should be 'list1'
例如:这里我的查询是 key=1,输出应该是 'list1'
I wrote
我写
id1.entrySet().stream().filter( e -> e.getKey() == 1);
But I don't know how to retrieve as a list as output of this stream operation.
但我不知道如何检索作为此流操作的输出的列表。
Q2) Again I want to apply a filter condition on the key in hashmap and retrieve the corresponding list of lists.
Q2)我想再次对 hashmap 中的键应用过滤条件并检索相应的列表列表。
Eg: Here My query is key=1%(i.e key can be 1,10,15), and output should be 'list1','list2','list3'(list of lists).
例如:这里我的查询是key=1%(即key可以是1、10、15),输出应该是'list1'、'list2'、'list3'(列表列表)。
采纳答案by Eran
If you are sure you are going to get at most a single element that passed the filter (which is guaranteed by your filter), you can use findFirst
:
如果您确定最多只能获得一个通过过滤器的元素(由您的过滤器保证),您可以使用findFirst
:
Optional<List> o = id1.entrySet()
.stream()
.filter( e -> e.getKey() == 1)
.map(Map.Entry::getValue)
.findFirst();
In the general case, if the filter may match multiple Lists, you can collect them to a List of Lists :
在一般情况下,如果过滤器可能匹配多个 Lists,您可以将它们收集到 List of Lists :
List<List> list = id1.entrySet()
.stream()
.filter(.. some predicate...)
.map(Map.Entry::getValue)
.collect(Collectors.toList());
回答by fge
What you need to do is create a Stream
out of the Map
's .entrySet()
:
您需要做的是Stream
从Map
's 中创建一个.entrySet()
:
// Map<K, V> --> Set<Map.Entry<K, V>> --> Stream<Map.Entry<K, V>>
map.entrySet().stream()
From the on, you can .filter()
over these entries. For instance:
从那时起,您可以.filter()
覆盖这些条目。例如:
// Stream<Map.Entry<K, V>> --> Stream<Map.Entry<K, V>>
.filter(entry -> entry.getKey() == 1)
And to obtain the values from it you .map()
:
并从中获取值.map()
:
// Stream<Map.Entry<K, V>> --> Stream<V>
.map(Map.Entry::getValue)
Finally, you need to collect into a List
:
最后,您需要收集到一个List
:
// Stream<V> --> List<V>
.collect(Collectors.toList())
If you have only one entry, use this instead (NOTE: this code assumes that there is a value; otherwise, use .orElse()
; see the javadoc of Optional
for more details):
如果您只有一个条目,请改用它(注意:此代码假定存在一个值;否则,请使用.orElse()
;有关更多详细信息,请参阅的javadocOptional
):
// Stream<V> --> Optional<V> --> V
.findFirst().get()
回答by user2336315
For your Q2, there are already answers to your question. For your Q1, and more generally when you know that the key's filtering should give a unique value, there's no need to use Streams at all.
对于您的 Q2,您的问题已经有了答案。对于您的 Q1,更一般地说,当您知道键的过滤应提供唯一值时,根本不需要使用 Streams。
Just use get
or getOrDefault
, i.e:
只需使用get
or getOrDefault
,即:
List<String> list1 = id1.getOrDefault(1, Collections.emptyList());
回答by Basit
You can also do it like this
你也可以这样做
public Map<Boolean, List<Student>> getpartitionMap(List<Student> studentsList) {
List<Predicate<Student>> allPredicates = getAllPredicates();
Predicate<Student> compositePredicate = allPredicates.stream()
.reduce(w -> true, Predicate::and)
Map<Boolean, List<Student>> studentsMap= studentsList
.stream()
.collect(Collectors.partitioningBy(compositePredicate));
return studentsMap;
}
public List<Student> getValidStudentsList(Map<Boolean, List<Student>> studentsMap) throws Exception {
List<Student> validStudentsList = studentsMap.entrySet()
.stream()
.filter(p -> p.getKey() == Boolean.TRUE)
.flatMap(p -> p.getValue().stream())
.collect(Collectors.toList());
return validStudentsList;
}
public List<Student> getInValidStudentsList(Map<Boolean, List<Student>> studentsMap) throws Exception {
List<Student> invalidStudentsList =
partionedByPredicate.entrySet()
.stream()
.filter(p -> p.getKey() == Boolean.FALSE)
.flatMap(p -> p.getValue().stream())
.collect(Collectors.toList());
return invalidStudentsList;
}
With flatMap
you will get just List<Student>
instead of List<List<Student>>
.
有了flatMap
你,你会得到 justList<Student>
而不是List<List<Student>>
。
Thanks
谢谢
回答by Shreya Mour
Using keySet-
使用 keySet-
id1.keySet().stream()
.filter(x -> x == 1)
.map(x -> id1.get(x))
.collect(Collectors.toList())