Reputation: 569
I have this map 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..
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();
Upvotes: 1
Views: 1144
Reputation: 2424
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
Upvotes: 0
Reputation: 56433
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[] 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));
}
Upvotes: 4