简体   繁体   中英

Sort LinkedHashMap by key and convert to List in Android

I have a HashMap like bellow:

{ 1 = "", 0 = Ecrivez, 2 = Hello }

I want to convert it into an ArrayList sorted by key like this:

Ecrivez, "", Hello

I used the following code but it doesn't work.

List sortedKeys = new ArrayList(testhmap.values());
Collections.sort(sortedKeys);

I see two ways of doing this:

// Using TreeMap (Java 1.2+)
List<String> list = new ArrayList<>(new TreeMap<>(map).values());
// Using Stream (Java 8+)
List<String> list = map.entrySet().stream().sorted(Entry.comparingByKey())
                    .map(Entry::getValue).collect(Collectors.toList());

Both of the above will turn map {1=, 0=Ecrivez, 2=Hello} into list [Ecrivez, , Hello]

See this code run live at IdeOne.com .

Is this what you are expecting?

public static void main(String[] args) {
    HashMap<Integer, String> hashMap = new LinkedHashMap<>();
    hashMap.put(1, "");
    hashMap.put(0, "Ecrivez");
    hashMap.put(2, "Hello");

    System.out.println("Before sort: " + hashMap.values());
    List<String> list = hashMap.keySet().stream().sorted().map(key -> hashMap.get(key))
        .collect(Collectors.toList());
    System.out.println("After sort: " + list);
  }

Output is as below:

Before sort: [, Ecrivez, Hello]
After sort: [Ecrivez, , Hello]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM