차근차근/JAVA JSP
map의 value값으로 정렬 .내림차순
http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-
public class Testing {
public static void main(String[] args) {
HashMap<String,Double> map = new HashMap<String,Double>();
ValueComparator bvc = new ValueComparator(map);
TreeMap<String,Double> sorted_map = new TreeMap<String,Double>(bvc);
map.put("A",99.5);
map.put("B",67.4);
map.put("C",67.4);
map.put("D",67.3);
System.out.println("unsorted map: "+map);
sorted_map.putAll(map);
System.out.println("results: "+sorted_map);
}
}
class ValueComparator implements Comparator<String> {
Map<String, Double> base;
public ValueComparator(Map<String, Double> base) {
this.base = base;
}
// Note: this comparator imposes orderings that are inconsistent with equals.
public int compare(String a, String b) {
if (base.get(a) >= base.get(b)) {
return -1;
} else {
return 1;
} // returning 0 would merge keys
}
}
Here's a generic-friendly version you're free to use:
import java.util.*;
public class MapUtil
{
public static <K, V extends Comparable<? super V>> Map<K, V>
sortByValue( Map<K, V> map )
{
List<Map.Entry<K, V>> list =
new LinkedList<Map.Entry<K, V>>( map.entrySet() );
Collections.sort( list, new Comparator<Map.Entry<K, V>>()
{
public int compare( Map.Entry<K, V> o1, Map.Entry<K, V> o2 )
{
return (o1.getValue()).compareTo( o2.getValue() );
}
} );
Map<K, V> result = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry : list)
{
result.put( entry.getKey(), entry.getValue() );
}
return result;
}
}
And an associated JUnit4 test so you don't have to take my word for it:
import java.util.*;
import org.junit.*;
public class MapUtilTest
{
@Test
public void testSortByValue()
{
Random random = new Random(System.currentTimeMillis());
Map<String, Integer> testMap = new HashMap<String, Integer>(1000);
for(int i = 0 ; i < 1000 ; ++i) {
testMap.put( "SomeString" + random.nextInt(), random.nextInt());
}
testMap = MapUtil.sortByValue( testMap );
Assert.assertEquals( 1000, testMap.size() );
Integer previous = null;
for(Map.Entry<String, Integer> entry : testMap.entrySet()) {
Assert.assertNotNull( entry.getValue() );
if (previous != null) {
Assert.assertTrue( entry.getValue() >= previous );
}
previous = entry.getValue();
}
}
}
Java 7 Version
public static <K, V extends Comparable<? super V>> Map<K, V>
sortByValue( Map<K, V> map )
{
List<Map.Entry<K, V>> list =
new LinkedList<>( map.entrySet() );
Collections.sort( list, new Comparator<Map.Entry<K, V>>()
{
@Override
public int compare( Map.Entry<K, V> o1, Map.Entry<K, V> o2 )
{
return (o1.getValue()).compareTo( o2.getValue() );
}
} );
Map<K, V> result = new LinkedHashMap<>();
for (Map.Entry<K, V> entry : list)
{
result.put( entry.getKey(), entry.getValue() );
}
return result;
}
Java 8 Version
public static <K, V extends Comparable<? super V>> Map<K, V>
sortByValue( Map<K, V> map )
{
Map<K,V> result = new LinkedHashMap<>();
Stream <Entry<K,V>> st = map.entrySet().stream();
st.sorted(Comparator.comparing(e -> e.getValue()))
.forEach(e ->result.put(e.getKey(),e.getValue()));
return result;
}
http://antonio91.egloos.com/viewer/5527386
[Java] Map, Table의 value 값 정렬
http://ekfqkqhd.tistory.com/entry/Java-HashMap-Value-%EC%A0%95%EB%A0%AC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class Test { public static void main(String[] args) { Map<string,integer> map = new HashMap<string,integer>(); map.put( "a" , 3 ); map.put( "b" , 2 ); map.put( "c" , 1 ); System.out.println( "------------sort 전 -------------" ); System.out.println(map); Iterator it = Test.sortByValue(map).iterator(); System.out.println( "---------sort 후------------" ); while (it.hasNext()){ String temp = (String) it.next(); System.out.println(temp + " = " + map.get(temp)); } //System.out.println(map); } public static List sortByValue( final Map map){ List<string> list = new ArrayList(); list.addAll(map.keySet()); Collections.sort(list, new Comparator(){ public int compare(Object o1,Object o2){ Object v1 = map.get(o1); Object v2 = map.get(o2); return ((Comparable) v1).compareTo(v2); } }); Collections.reverse(list); // 주석시 오름차순 return list; } } </string></string,integer></string,integer>
|
http://www.xinotes.net/notes/note/306/
When you use a TreeMap
, the entries in the Map
is sorted by the keys.
This following code outputs the elements of the map sorted by value.
import java.util.*; @SuppressWarnings("unchecked") // for JDK 1.5 and above public class HashMapSort { public static void main(String[] args) { Map m = new HashMap(); m.put("a", "some"); m.put("b", "random"); m.put("c", "words"); m.put("d", "to"); m.put("e", "be"); m.put("f", "sorted"); m.put("g", "by"); m.put("h", "value"); for (Iterator i = sortByValue(m).iterator(); i.hasNext(); ) { String key = (String) i.next(); System.out.printf("key: %s, value: %s\n", key, m.get(key)); } } public static List sortByValue(final Map m) { List keys = new ArrayList(); keys.addAll(m.keySet()); Collections.sort(keys, new Comparator() { public int compare(Object o1, Object o2) { Object v1 = m.get(o1); Object v2 = m.get(o2); if (v1 == null) { return (v2 == null) ? 0 : 1; } else if (v1 instanceof Comparable) { return ((Comparable) v1).compareTo(v2); } else { return 0; } } }); return keys; } }
The output is:
key: e, value: be
key: g, value: by
key: b, value: random
key: a, value: some
key: f, value: sorted
key: d, value: to
key: h, value: value
key: c, value: words
http://okjsp.net/seq/99088#1410485932879
Map param = new HashMap();
param.put("A", "2");
param.put("B", "1");
param.put("C", "4");
param.put("D", "3");
Collection cols = param.values();
List temps = new ArrayList(cols);
Collections.sort(temps);
if (temps != null) {
for (int i = 0, j = temps.size() ; i < j ; i++) {
System.out.println(i + "번째 값은 : " + (String)temps.get(i));
}
}
위에는 오름차순 정렬이구요
내림차순 정렬하실려면
Collections.sort(temps, Collections.reverseOrder());
이걸루 바꾸세요.
입력받은 그대로 map에 넣어 출력하고 싶으면
LinkedHashMap
'차근차근 > JAVA JSP' 카테고리의 다른 글
에러 (0) | 2014.09.17 |
---|---|
09.05 (화) -> 09월 05일 (화요일) (0) | 2014.09.12 |
[Java] Map, Table의 value 값 정렬 (0) | 2014.09.12 |
StringTokenizer 와 String.split() (0) | 2014.09.11 |
자바 한글 UTF Normalize 예제 (0) | 2014.09.11 |
'차근차근/JAVA JSP'의 다른글
- 현재글map의 value값으로 정렬 .내림차순