我目前正在使用Multiset来保存最多三个数字。我需要检查一下:
以下是我目前的代码。在这种情况下,团队是Multimap,points是Multiset:
for(int a = 0; a <= team.keySet().size(); a++)
{
if(points.count(a) > 1)
{
// Point 1
}
else if(points.size == 1)
{
// Point 3
}
else if(points.isEmpty()
{
// Point 4
}
}
我一直坚持如何实施第2点 - 任何建议?
答案 0 :(得分:0)
怎么样:
Multiset<Integer> tmp = HashMultiset.create();
for(int a = 0; a <= team.keySet().size(); a++) {
tmp.add(points.count(a));
}
现在查看tmp是否具有count()&gt;的值1
答案 1 :(得分:0)
在for
- 循环之前,声明一个
Map<Integer,Boolean> numEntries = new HashMap<Integer,Boolean>();
如果某个数字a包含键条目,则此地图将包含true
值。
然后,在最后else if
之后,您可以添加:
if (numEntries.containsKey(points.count(a)) && numEntries.get(points.count(a)){
//Point 2, some other number has already had this number of entries
} else {
numEntries.put(points.count(a), true); // a has this number of entries!
//Or do something more complicated to save that it was the number a that
//"was here first" (you could change the value type from Boolean to Integer
//or something to save this information)
}
如果大量使用points.count(a),我会考虑将它变成局部变量。
编辑之前有错误的逻辑,上面的代码现在应该正常运行
答案 2 :(得分:0)
我真的不明白你为什么要在Multimap的keySet大小上进行循环,然后检查递增计数器的计数...
这就是为什么我假设您提到Multimap
,因为您希望从Multimap#keys()
获取Multiset
。这里有示例代码:
final class MultisetFromMultimap {
public static void main(String[] args) {
Multimap<Integer, Integer> team = ImmutableMultimap.of(
1, 1,
1, 2,
2, 22,
2, 33,
3, 0);
test(team, 2, 1);
test(ImmutableMultimap.of(42, 42), 42, 1);
test(ImmutableMultimap.<Integer, Integer>of(), 0, 1);
}
private static void test(Multimap<Integer, Integer> team,
Integer test1, Integer test2) {
System.out.println("multimap: " + team);
Multiset<Integer> points = team.keys();
System.out.println("multiset: " + points);
boolean ad1 = points.count(test1) > 1; // point 1
boolean ad2 = points.count(test1) == points.count(test2); // point 2
boolean ad3 = points.size() == 1; // point 3
boolean ad4 = points.isEmpty(); // point 4
System.out.println("answers: " + Arrays.asList(ad1, ad2, ad3, ad4));
}
}
产生以下输出:
multimap: {1=[1, 2], 2=[22, 33], 3=[0]}
multiset: [1 x 2, 2 x 2, 3]
answers: [true, true, false, false]
multimap: {42=[42]}
multiset: [42]
answers: [false, false, true, false]
multimap: {}
multiset: []
answers: [false, true, false, true]