面临一个问题,我需要将元素放在两个不同的地图中,然后经过所有这些并将if条件放在最后一个Map的最后一个元素上。
我在这里尝试过代码:
private Map<Integer, String> testing1 = new TreeMap<>();
private Map<Integer, String> testing2 = new TreeMap<>();
testing1.put(1, "one");
testing1.put(2, "two");
testing2.put(3, "three");
testing2.put(4, "four");
现在我有两个for循环,我想检查两个for循环是否现在都有最后一个元素: 我尝试过.size(),但这对Map
没有帮助for (Map.Entry<Integer,String> something: testing1.entrySet()) {
for (Map.Entry<Integer,String> something2: testing2.entrySet()) {
if(){
}
}
}
答案 0 :(得分:4)
我猜,这对你真的很有用。
TreeMap的lastKey 方法。
Map<Integer, String> testing1 = new TreeMap<>();
Map<Integer, String> testing2 = new TreeMap<>();
testing1.put(1, "one");
testing1.put(2, "two");
testing2.put(3, "three");
testing2.put(4, "four");
int lastKey1 = ((TreeMap<Integer, String>) testing1).lastKey();
int lastKey2 = ((TreeMap<Integer, String>) testing2).lastKey();
for (Map.Entry<Integer,String> something: testing1.entrySet()) {
for (Map.Entry<Integer,String> something2: testing2.entrySet()) {
if(something.getKey() == lastKey1 && something2.getKey() == lastKey2){
// do your work
}
}
}