我有以下代码:
public class Tester {
public static void main(String[] args) {
HashMap map = new HashMap();
map.put(1, "one");
map.put(2, "twp");
map.put(2, "two2");
int highest = Integer.MIN_VALUE;
String highestString = null;
int secondHighest = Integer.MIN_VALUE;
String secondHighestString = null;
if (highest == Integer.MIN_VALUE){
highest = Collections.max(map.keySet() );
highestString = map.get(highest);
map.remove(highest);
}
if (secondHighest == Integer.MIN_VALUE ){
secondHighest = Collections.max(map.keySet() );
secondHighestString = map.get(secondHighest);
map.remove(secondHighest);
}
System.out.println(highest + highestString);
System.out.println(secondHighest + secondHighestString);
}
}
我无法像我尝试的那样返回两个最高值,因为似乎不可能只用相同的键删除一个值,而且我还尝试交换它们(制作HashMap也不是最佳选择).我应该尝试使用任何其他种类的收藏吗?
我也尝试过:
TreeSet set = new TreeSet();
set.add(new Tete("name1", 1));
set.add(new Tete("name2",4));
set.add(new Tete("name3",4));
set.add(new Tete("name4",12));
System.out.println(set.size());
假设类“ Tete”仅包含一个String和一个Integer,则设置大小仅为3,而不是4.而且,如果我打印每个数字,则不会打印“ name3”,因此无法返回三个最大值,例如,只会出现“ name4”,“ name2”和“ name1”,而“ name3”大于“ name1” ”
解决方法:
为了解决排名问题,我将编写一个自定义类,如下所示:
public class TopsCollection {
private final TreeMap> map
= new TreeMap<>((lhv, rhv) -> rhv.compareTo(lhv));
public TopsCollection() {}
public void add(Integer score, D name) {
List vals = map.get(score);
if (vals == null) {
vals = new ArrayList<>();
map.put(score, vals);
}
vals.add(name);
}
public List getTops(int n) {
return map.
values().
stream().
limit(n).
reduce(new ArrayList(), (lhv, rhv) -> {
lhv.addAll(rhv);
return lhv;
});
}
}
用法:
TopsCollection tc = new TopsCollection<>();
tc.add(12, "nome4");
tc.add(1, "nome1");
tc.add(4, "nome3");
tc.add(4, "nome2");
List tops = tc.getTops(2); // contains 3 elements: nome4, nome3, nome2
备注:
这种特定的实现可以返回任何数量的与最高排名相关的条目.
还应注意,因为TopsCollection由TreeMap类支持,所以add(…)方法所花费的时间与log(n)成比例.
如果需要,TopCollection可以实现Collection< T>.界面,使其可以作为真正的收藏夹使用.
标签:java
来源: https://codeday.me/bug/20191120/2047828.html