作者:Mister-Sky_724 | 来源:互联网 | 2023-05-19 18:20
对HashMap按value值的大小进行排序,方法如下。
import java.util.*;public class MapUtil{ public static > Map sortByValue( Map map ) { List> list = new LinkedList>( map.entrySet() ); Collections.sort( list, new Comparator>() { public int compare( Map.Entry o1, Map.Entry o2 ) { return (o1.getValue()).compareTo( o2.getValue() ); } } ); Map result = new LinkedHashMap(); for (Map.Entry 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 testMap = new HashMap(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 entry : testMap.entrySet()) {
Assert.assertNotNull( entry.getValue() );
if (previous != null) {
Assert.assertTrue( entry.getValue() >= previous );
}
previous = entry.getValue();
}
}
}
Java 7 Version:
public static > Map
sortByValue( Map map )
{
List> list =
new LinkedList<>( map.entrySet() );
Collections.sort( list, new Comparator>()
{
@Override
public int compare( Map.Entry o1, Map.Entry o2 )
{
return ( o1.getValue() ).compareTo( o2.getValue() );
}
} );
Map result = new LinkedHashMap<>();
for (Map.Entry entry : list)
{
result.put( entry.getKey(), entry.getValue() );
}
return result;
}
Java 8 Version:
public static > Map
sortByValue( Map map )
{
Map result = new LinkedHashMap<>();
Stream> st = map.entrySet().stream();
st.sorted( Map.Entry.comparingByValue() )
.forEachOrdered( e -> result.put(e.getKey(), e.getValue()) );
return result;
}
在JAVA8版本中,
st.sorted(Map.Entry.comparingByValue()).forEachOrdered(e->result.put(e.getKey(), e.getValue()));
也可写成:
st.sorted(Comparator.comparing(e -> e.getValue())).forEach(e -> result.put(e.getKey(), e.getValue()));
以上是按照升序排序的,按照降序排序方法如下:
import java.util.*;
import java.util.stream.Stream;
public class MapUtil {
public static > Map sortByValue( Map map) {
Map result = new LinkedHashMap<>();
Stream> st = map.entrySet().stream();
Comparator ok = new Comparator>()
{
public int compare( Map.Entry o1, Map.Entry o2 )
{
return (o2.getValue()).compareTo( o1.getValue() );
}
};
st.sorted(ok).forEachOrdered(e->result.put(e.getKey(), e.getValue()));
return result;
}
}