[英]Counting objects with a same property value
I'm creating a poker rank solver and I have to count cards with same suit or same rank in a set of cards. 我正在创建一个扑克排名求解器,我必须在一组牌中计算具有相同套装或同等级别的牌。 Here I create
HashMap
and increment value if multiple ranks are in the set. 在这里,如果集合中有多个排名,我会创建
HashMap
并增加值。
private boolean isFourOfAKind() {
Map<RANK, Integer> rankDuplicates = new HashMap<>();
for(Card card : cards) {
rankDuplicates.put(card.getRank(), rankDuplicates.getOrDefault(card.getRank(), 0) + 1);
}
return rankDuplicates.containsValue(4);
}
I was wondering is it possible using streams do exact same things with java streams. 我想知道是否有可能使用流与java流完全相同的事情。 It would look something like this:
它看起来像这样:
private boolean isFourOfAKind() {
Map<RANK, Integer> rankDuplicates = cards.stream()
.map(Card::getRank)
.collect(Collectors.toMap(/*...something goes here..*/)); // of course this is very wrong, but you can see what I'm aiming at.
return rankDuplicates.containsValue(4);
}
It looks like you are looking for something like 看起来你正在寻找类似的东西
return cards.stream()
.collect(Collectors.toMap(Card::getRank, e -> 1, Integer::sum))
// keyMapper, valueMapper, mergeFunction
.containsValue(4);
Another variant with groupingBy
: groupingBy
另一个变种:
import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;
...
private boolean isFourOfAKind() {
return cards.stream()
.collect(groupingBy(Card::getRank, counting()))
.containsValue(4L);
}
Basically you group the card by the ranks so that you have a Map<Rank, List<Card>>
基本上你按照等级对牌进行分组,这样你就可以得到
Map<Rank, List<Card>>
Then you use the downstream collector counting()
to map each list to its number of elements, so that the final result is a Map<Rank, Long>
(you could also use summingInt(i -> 1)
instead of counting()
if you really need to have a Map<Rank, Integer>
). 然后使用下游收集器
counting()
将每个列表映射到其元素数,以便最终结果是Map<Rank, Long>
(您也可以使用summingInt(i -> 1)
而不是summingInt(i -> 1)
counting()
你真的需要一个Map<Rank, Integer>
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.