Date: 2016mar9
Update: 2025sep27
Language: Java
Keywords: to
Q. Java: Convert a HashMap's values into a sorted ArrayList?
A. ArrayList's constructor takes a HashSet then use Collections.sort()
as shown in this full example:
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Collections;
class Demo {
public static final void main(String []args) {
HashMap<String,Integer> h = new HashMap<>();
h.put("three", 3);
h.put("two", 2);
h.put("one", 1);
ArrayList<Integer> vals = new ArrayList<>(h.values()); // STEP 1
Collections.sort(vals); // STEP 2
System.out.println("vals=" + vals);
}
}
Output:
vals=[1, 2, 3]
h.values() gives it as HashSet.