![](/img/trans.png)
[英]Check whether list of custom objects have same value for a property in Java 8
[英]Counting objects with a same property value
我正在創建一個撲克排名求解器,我必須在一組牌中計算具有相同套裝或同等級別的牌。 在這里,如果集合中有多個排名,我會創建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);
}
我想知道是否有可能使用流與java流完全相同的事情。 它看起來像這樣:
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);
}
看起來你正在尋找類似的東西
return cards.stream()
.collect(Collectors.toMap(Card::getRank, e -> 1, Integer::sum))
// keyMapper, valueMapper, mergeFunction
.containsValue(4);
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);
}
基本上你按照等級對牌進行分組,這樣你就可以得到Map<Rank, List<Card>>
然后使用下游收集器counting()
將每個列表映射到其元素數,以便最終結果是Map<Rank, Long>
(您也可以使用summingInt(i -> 1)
而不是summingInt(i -> 1)
counting()
你真的需要一個Map<Rank, Integer>
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.