what is the best way to get a sub HashMap based on a list of Keys?

With Java8 streams, there is a functional (elegant) solution. If keys is the list of keys to keep and map is the source Map. keys.stream() .filter(map::containsKey) .collect(Collectors.toMap(Function.identity(), map::get)); Complete example: List<Integer> keys = new ArrayList<>(); keys.add(2); keys.add(3); keys.add(42); // this key is not in the map Map<Integer, String> map = new HashMap<>(); map.put(1, “foo”); map.put(2, … Read more

Sorting the Map in descending order based on the value [duplicate]

Since you can have duplicate values you shouldn’t be using a Set at all. Change to a List and sort it instead. Your entriesSortedByValues would look something like this: static <K,V extends Comparable<? super V>> List<Entry<K, V>> entriesSortedByValues(Map<K,V> map) { List<Entry<K,V>> sortedEntries = new ArrayList<Entry<K,V>>(map.entrySet()); Collections.sort(sortedEntries, new Comparator<Entry<K,V>>() { @Override public int compare(Entry<K,V> e1, Entry<K,V> … Read more

How does ConcurrentHashMap work internally?

I would read the source of ConcurrentHashMap as it is rather complicated in the detail. In short it has Multiple partitions which can be locked independently. (16 by default) Using concurrent Locks operations for thread safety instead of synchronized. Has thread safe Iterators. synchronizedCollection’s iterators are not thread safe. Does not expose the internal locks. … Read more