Retrieving the last entrry of a LinkedHashMap using reflection
LinkedHashMap<String, String> data = new LinkedHashMap<>();
data.put("a", "apple");
data.put("b", "banana");
try {
var field = data.getClass().getDeclaredField("tail");
field.setAccessible(true);
Map.Entry<String, String> lastEntry = (Map.Entry<String, String>) field.get(data);
String lastKey = lastEntry.getKey();
String lastValue = lastEntry.getValue();
} catch (NoSuchFieldException | IllegalAccessException ex) {
ex.printStackTrace();
}
Sorting a Map by its values
public static <K, V extends Comparable<V>> Map<K, V> orderByValue(Map<K, V> source) {
Map<K, V> ordered = new LinkedHashMap<>();
source.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.forEach(e -> ordered.put(e.getKey(), e.getValue()));
return ordered;
}
Sorting a Map by its keys
import java.util.*;
import java.util.stream.Collectors;
public class MapSortingExample {
public static void countSalaries(int count, int[] amounts) {
Map<Integer, Integer> freqMap = new LinkedHashMap<>();
for (int i = 0; i < count; i++) {
freqMap.merge(amounts[i], 1, Integer::sum);
}
Map<Integer, Integer> sorted = orderByKeyDesc(freqMap);
System.out.println(sorted);
}
public static <K extends Comparable<K>, V> Map<K, V> orderByKeyDesc(Map<K, V> source) {
Map<K, V> result = new LinkedHashMap<>();
source.entrySet()
.stream()
.sorted((e1, e2) -> e2.getKey().compareTo(e1.getKey()))
.forEach(e -> {
System.out.println("key:" + e.getKey() + " value:" + e.getValue());
result.put(e.getKey(), e.getValue());
});
return result;
}
public static void main(String[] args) {
int total = 5;
int[] salaries = {1000, 2000, 1000, 3000, 2000};
countSalaries(total, salaries);
}
}
Output:
key:3000 value:1
key:2000 value:2
key:1000 value:2
{3000=1, 2000=2, 1000=2}