'Sort a Map in descending order based on value of arraylist in Java
I have a Map of type
static Map<String, ArrayList<String>> Container = new HashMap<String, ArrayList<String>>();
The value array list has two elements, the first index is an extension and the second is size,
Container : {
C:\HTML\viewer\files\output\ViewerJS\commons-io-2.11.0-src (2).zip=[zip, 919362],
C:\HTML\viewer\files\jar_files (2).zip=[zip, 345068],
C:\HTML\viewer\files\output\ViewerJS\rar1.rar=[rar, 1],
C:\HTML\viewer\files\output\files.zip=[zip, 10184010],
C:\HTML\viewer\files\check2.zip=[zip, 1]
}
I want the map to be sorted in descending order based on the number in index 1 of the map value which is the size which is also of type STRING.
A little help would be much appreciated, Thank you.
Solution 1:[1]
This uses a TreeMap and a utility function(addElementsToMap) that would update your map.
Note: A Comparator is provided at map creation time.
public class DriverClass {
private static Map<Integer, ArrayList<String>> container = new TreeMap<>((o1, o2) -> (o2 < o1) ? -1 : 1);
public static void main(String[] args) {
DriverClass driver = new DriverClass();
String[] elementsList = driver.collectElements();
driver.addElementsToMap(elementsList);
container.entrySet().forEach(e -> System.out.println(e.getKey() + " ----- " + e.getValue()));
}
private void addElementsToMap(String[] elementsList) {
int i = 0;
for (int j = elementsList.length/2; j <= elementsList.length-1; j++) {
int size = Integer.parseInt(elementsList[i+1].replaceAll("]", ""));
container.put(size, new ArrayList<>(Arrays.asList(elementsList[i], elementsList[i+1])));
i += 2;
}
}
private String[] collectElements() {
return new String[] {
"C:\\HTML\\viewer\\files\\output\\ViewerJS\\commons-io-2.11.0-src (2).zip=[zip", "919362]",
"C:\\HTML\\viewer\\files\\jar_files (2).zip=[zip", "345068]",
" C:\\HTML\\viewer\\files\\output\\ViewerJS\\rar1.rar=[rar", "1]",
"C:\\HTML\\viewer\\files\\output\\files.zip=[zip", "10184010]",
"C:\\HTML\\viewer\\files\\check2.zip=[zip", "1]"};
}
}
outputs:
10184010 ----- [C:\HTML\viewer\files\output\files.zip=[zip, 10184010]]
919362 ----- [C:\HTML\viewer\files\output\ViewerJS\commons-io-2.11.0-src (2).zip=[zip, 919362]]
345068 ----- [C:\HTML\viewer\files\jar_files (2).zip=[zip, 345068]]
1 ----- [C:\HTML\viewer\files\check2.zip=[zip, 1]]
1 ----- [ C:\HTML\viewer\files\output\ViewerJS\rar1.rar=[rar, 1]]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
