Yanshof
Yanshof

Reputation: 9926

how to get the first two items in HashMap<String, Integer>?

I've been trying a way to get the first 2 objects I've already tried using the transition to arrays, And also used in iterator

And every time I crash

    String[] strArr = (String[])map.keySet().toArray();    //crash
    Integer[] integerArr = (Integer[])map.values().toArray();


    String string1 = strArr[0];
    int value1 = integerArr[0];


    String string2 = strArr[1];
    int value2 = integerArr[1];

Upvotes: 1

Views: 633

Answers (2)

Leo Aso
Leo Aso

Reputation: 12463

There is no real concept of ordering in a HashMap. If you want insertion order, use a LinkedHashMap, and if you want lexicographic ordering, use a TreeMap. But anyway, here is how you would it.

String[] keys = new String[2];
Integer[] ints = new Integer[2]; // int[] also works
Iterator<Map.Entry<String, Integer>> it = map.entrySet().iterator();

for (int i = 0; i < 2 && it.hasNext(); i++) {
    Map.Entry<String,Integer> e = it.next();
    keys[i] = e.getKey();
    ints[i] = e.getValue();
}

Upvotes: 1

Eran
Eran

Reputation: 393781

First of all, you should realize there are no "first 2 objects" in a HashMap, since there is no ordering in a HashMap.

You can obtain arbitrary two entries that happen to be returned first when iterating over the HashMap:

String[] keys = new String[2];
Integer[] values = new Integer[2];
Iterator<Map.Entry<String,Integer>> iterator = map.entrySet().iterator();
for (int i = 0; i < 2 && iterator.hasNext(); i++) {
    Map.Entry<String,Integer> entry = iterator.next();
    keys[i] = entry.getKey();
    values[i] = entry.getValue();
}

Upvotes: 5

Related Questions