Skip to content
Advertisement

Check if last taken Map element is last

Faced a problem where I need to put elements in two different Maps and after go through all of them and put if condition on the last element of the last Map.

Here I have code I’ve tried:

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");

Now I have two for loops where I want to check if both for loops have last element right now: I have tried with .size() but that didn’t help with Map

for (Map.Entry<Integer,String> something: testing1.entrySet()) {
  for (Map.Entry<Integer,String> something2: testing2.entrySet()) {
     if(){
     }
  }
}

Advertisement

Answer

I guess, this will be really useful for you.

lastKey method of TreeMap.

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
         }
      }
    }

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement