1

I hava a structure Map :

Map<String, Double> map = new LinkedHashMap<>();

I don't know the key, but I want to pick up the first element and the last element, how can I achieve conveniently.

L. YanJun
  • 277
  • 3
  • 15

2 Answers2

2

Getting the first is easy - request an iterator and take it's next.

// Needs null checks etc.
String first = map.keySet().iterator().next();

Getting the last is covered in Java get last element of a collection.

Community
  • 1
  • 1
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
1

one way to do this:

    Map<String, Double> map = new LinkedHashMap<>();
    map.put("one", 2.0);
    map.put("two", 12.0);
    map.put("three", 44.0);
    String lKeyFirst = null;
    String lKeyLast = null;
    if (!map.isEmpty()){
      lKeyFirst = map.keySet().iterator().next();
      for(String key : map.keySet()){
        lKeyLast = key;
      }
      System.out.println("First key: " +lKeyFirst);
      System.out.println("Last key: " +lKeyLast);
    }

Output:

First key: one

Last key: three

of course isEmpty is never false in this case.

EDIT:

@Test
public void testMapOneValue() {
Map<String, Double> map = new LinkedHashMap<>();
map.put("one", 2.0);
String lKeyFirst = null;
String lKeyLast = null;
if (!map.isEmpty()){
  lKeyFirst = map.keySet().iterator().next();
  for(String key : map.keySet()){
    lKeyLast = key;
  }
  System.out.println("First key: " +lKeyFirst);
  System.out.println("Last key: " +lKeyLast);
}
}

Output:

First key: one

Last key: one

Community
  • 1
  • 1
nano_nano
  • 12,351
  • 8
  • 55
  • 83