Here is a summary of how to sort Map (HashMap) using value in java. Here, we are considering a situation where you want to sort the values of A_array at the same time using B_array. Since it is a form that sorts a list with an entry type of HashMap, it can be used with other Maps such as TreeMap.
Solution.java
import java.util.*;
class Solution {
public static void main(String[] args) {
int[] A_array = {1,6,3,10,5};
int[] B_array = {8,21,13,4,5};
tryComperator(A_array, B_array);
}
public static void tryComperator(int[] a, int[] b){
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
//Store the elements of the array in hashmap.
for (int i = 0; i < a.length; i++){
map.put(a[i], b[i]);
}
//Store each element of Hashmap in a list.
List<Map.Entry> mapValuesList = new ArrayList<Map.Entry>(map.entrySet());
//Try to output mapValuesList.(10=It seems that it is output in the form of 4.)
for (Map.Entry v: mapValuesList){
System.out.println("map>> "+v+",key>> "+v.getKey()+"value>> "+v.getValue());
}
//Instantiate the Comparator class
Comparator<Map.Entry> comparator = new Comparator<Map.Entry>() {
public int compare(Map.Entry entry1, Map.Entry entry2) {
return ((Integer) entry1.getValue()).compareTo((Integer) entry2.getValue());
}
};
//Sort using comparator.
Collections.sort(mapValuesList, comparator);
//Output for confirmation
for (Map.Entry s : mapValuesList) {
System.out.println(s);
}
}
}
map>> 1=8,key>> 1value>> 8
map>> 3=13,key>> 3value>> 13
map>> 5=5,key>> 5value>> 5
map>> 6=21,key>> 6value>> 21
map>> 10=4,key>> 10value>> 4
10=4
5=5
1=8
3=13
6=21
It was output in ascending order of value.
Reference: http://kevin3sei.blog95.fc2.com/blog-entry-159.html
Recommended Posts