TreeMap对key排序,下面我们实现Map对value排序:
import java.util.*;
import java.util.stream.Collectors;
/**
* Created by fhqplzj on 16-6-27.
*/
public class SortedByValue {
private static final String keyData = "said:that:with:from:have:were:they:will:would:about:year:this:been:their:percent:which:after:more:people:also";
private static final String valueData = "12856:8859:5422:4544:3600:3563:2980:2619:2567:2360:2286:2185:2182:2068:1950:1937:1927:1766:1731:1625";
public static void fillMap(Map<String, Integer> map) {
List<String> keys = Arrays.stream(keyData.split(":")).collect(Collectors.toList());
List<Integer> values = Arrays.stream(valueData.split(":")).map(Integer::new).collect(Collectors.toList());
Collections.shuffle(keys);
Collections.shuffle(values);
keys.forEach(key -> map.put(key, values.get(keys.indexOf(key))));
map.entrySet().forEach(System.out::println);
}
public static void main(String[] args) {
//填充map,map的values是乱序的
Map<String, Integer> map = new HashMap<>();
fillMap(map);
//第一步:将map转化为list
List<Map.Entry<String, Integer>> list = map.entrySet().stream().sorted(((o1, o2) -> o2.getValue().compareTo(o1.getValue()))).collect(Collectors.toList());
//第二步:将list转化为LinkedHashMap
Map<String, Integer> result = new LinkedHashMap<>();
list.forEach(stringIntegerEntry -> result.put(stringIntegerEntry.getKey(), stringIntegerEntry.getValue()));
//第三步:打印结果看看
char[] chars = new char[50];
Arrays.fill(chars, '*');
System.out.println(String.valueOf(chars) + "分割线" + String.valueOf(chars));
result.entrySet().forEach(System.out::println);
}
}
实验结果为:
which=2980
been=5422
will=2360
year=2619
more=8859
this=1766
about=4544
their=1937
also=1927
percent=2185
people=3563
that=1625
with=1950
would=12856
were=2182
have=2286
from=2567
after=2068
said=1731
they=3600
**************************************************分割线**************************************************
would=12856
more=8859
been=5422
about=4544
they=3600
people=3563
which=2980
year=2619
from=2567
will=2360
have=2286
percent=2185
were=2182
after=2068
with=1950
their=1937
also=1927
this=1766
said=1731
that=1625