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

List<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

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 按 age 倒序

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));
posted @ 2019-08-18 00:56  O&#39;Neal  阅读(512)  评论(0编辑  收藏  举报