Java 常用的转换、排序
1 字符串、数组、集合的转换
定义字符串数组 string[] strarr
string[] strarr = {"red", "green", "blue"};
1.1 字符串数组转集合
list<string> list = arrays.aslist(strarr);
1.2 字符串集合转数组
string[] strarrnew = list.toarray(new string[0]);
1.3 字符串集合转逗号分隔的字符串
string str = string.join(",", list);
1.4 逗号分隔的字符串转字符串集合
list<string> list2 = new arraylist<>(arrays.aslist(str.split(",")));
1.5 对象集合转 map<string, integer>
定义对象 person
private static class person { private string name; private integer age; }
定义对象 person 的集合 list
对象集合转为 maplist<person> personlist = lists.newarraylist(
new person("jordan", 38),
new person("o'neal", 34),
new person("james", 31),
new person("kobe", 34),
new person("trace", 32)
);
map<string, integer> personmap = personlist.stream().collect(collectors.tomap(person::getname, person::getage));
2 list、map 的排序
2.1 list
list.sort(comparator.naturalorder());
2.2 list
personlist.sort(comparator.comparing(person::getage).reversed());
2.3 map<string, integer> 按 value 倒序
personmap.entryset().stream()
.sorted(map.entry.comparingbyvalue(comparator.reverseorder()))
.collect(collectors.tomap(map.entry::getkey, map.entry::getvalue, (o, n) -> o, linkedhashmap::new));