Home >Java >javaTutorial >Example code for sorting and outputting by value in Java's Map collection

Example code for sorting and outputting by value in Java's Map collection

高洛峰
高洛峰Original
2017-01-19 09:45:061492browse

The example code for sorting and outputting by value in the Java Map collection

import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
 
public class Test {
 
public static void main(String[] args) {
Map<String ,Integer> map = new HashMap<String ,Integer>();
map.put("aa", 22);
map.put("bb", 11);
map.put("cc", 44);
map.put("dd", 33);
map.put("ee", 55);
Map.Entry[] entries= getSortedHashtableByValue(map);
for(int i=0;i<entries.length;i++)
{
System.out.println(entries[i]);
}
}
 
public static Map.Entry[] getSortedHashtableByValue(Map map) {
Set set = map.entrySet();
Map.Entry[] entries = (Map.Entry[]) set.toArray(new Map.Entry[set.size()]);
Arrays.sort(entries, new Comparator() {
public int compare(Object arg0, Object arg1) {
Long key1 = Long.valueOf(((Map.Entry) arg0).getValue().toString());
Long key2 = Long.valueOf(((Map.Entry) arg1).getValue().toString());
return key1.compareTo(key2);
}
});
return entries;
}
 
}

The above example code for sorting and outputting by value in the Java Map collection is all the content shared by the editor. , I hope it can give you a reference, and I also hope that everyone will support the PHP Chinese website.

For more related articles on example codes for sorting and outputting by value in Java's Map collection, please pay attention to the PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn