[英]is there a way to get values of a map of pair and value by the key pair only?
I have this map static Map<Pair<String,Integer>, Integer> wordTopic = new HashMap<>();
我有这张地图static Map<Pair<String,Integer>, Integer> wordTopic = new HashMap<>();
Basically it's a matrix , and i want all the values of specific string(the key of the pair)..AKA all the values of one row.. 基本上,这是一个矩阵,我想要特定字符串的所有值(该对的键).AKA一行的所有值。
This will get the sum of one row ,but i have no idea how to get the row itself,each value all in an array or something. 这将获得一行的总和,但我不知道如何获取该行本身,每个值都以数组或某种形式存在。
wordTopic.entrySet()
.stream()
.filter(e -> e.getKey().getKey().equals(key))
.mapToInt(Map.Entry::getValue)
.sum();
You can create a method as such: 您可以这样创建一个方法:
int[] getValuesByKey(Map<Pair<String,Integer>, Integer> map, String key) {
return map.entrySet()
.stream()
.filter(e -> e.getKey().getKey().equals(key))
.mapToInt(Map.Entry::getValue)
.toArray();
}
which given a map and a key will yield all the values where the entry key is equal to the provided key. 给定一个映射和一个键,它将产生所有值,其中输入键等于提供的键。
or if you want an Integer
array then you can do: 或者,如果您想要一个Integer
数组,则可以执行以下操作:
Integer[] getValuesByKey(Map<Pair<String,Integer>, Integer> map, String key) {
return map.entrySet()
.stream()
.filter(e -> e.getKey().getKey().equals(key))
.map(Map.Entry::getValue)
.toArray(Integer[]::new);
}
or if you want to retrieve a list. 或者如果您想检索列表。
List<Integer> getValuesByKey(Map<Pair<String,Integer>, Integer> map, String key) {
return map.entrySet()
.stream()
.filter(e -> e.getKey().getKey().equals(key))
.map(Map.Entry::getValue)
.collect(Collectors.toCollection(ArrayList::new));
}
You just have to add a collector at the end of the stream like that : 您只需要像这样在流的末尾添加一个收集器:
wordTopic.entrySet()
.stream()
.filter(e -> e.getKey().getKey().equals(key))
.mapToInt(Map.Entry::getValue)
.collect(Collectors.toList());
and here you go 然后你去
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.