Java8 Lambda表达式 ArrayList排序

Java7和 Java8对 List进行排序实例:

package com.dc.utils;

import java.util.*;
/**
 * @author hdc
 * @date 2019/2/25
 *
 * List 排序
 * Lambda表达式ArrayList排序
 */
public class ListUtil {
    public static void main(String[] args) {
        List humanList = new ArrayList<>();
        humanList.add(new Human("tom", 12));
        humanList.add(new Human("jerry", 1));
        humanList.add(new Human("jay", 23));
        System.out.println("排序前:" + humanList);
        //sortListUserJava7(humanList);
        sortListJava8(humanList);
        System.out.println("排序后:" + humanList);
    }

    /**
     * 使用java7对list进行排序
     * @param list
     *
     * 适用于 List>
     *        Collections.sort(list, new Comparator>(){
     *             @Override
     *             public int compare(Map map1, Map map2) {
     *                 String key1 = map1.get("value").toString();
     *                 String key2 = map2.get("value").toString();
     *                 return key1.compareTo(key2);
     *             }
     *         });
     */
    public static void sortListJava7(List list){
        Collections.sort(list, new Comparator(){
            @Override
            public int compare(Human human1, Human human2) {
                // 这里的 age需要不能是基本类型
                return human1.getAge().compareTo(human2.getAge());
            }
        });
    }

    /**
     * 使用java8对list进行排序
     * Lambda表达式排序法
     * @param list
     */
    public static void sortListJava8(List list){
        // 这里的 age需要不能是基本类型
        Collections.sort(list,(Human human1, Human human2) ->
                human1.getAge().compareTo(human2.getAge()));
    }



}
class Human {
    private String name;
    private Integer age;

    public Human(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Human{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

输出的结果是:

排序前:[Human{name='tom', age=12}, Human{name='jerry', age=1}, Human{name='jay', age=23}]
排序后:[Human{name='jerry', age=1}, Human{name='tom', age=12}, Human{name='jay', age=23}]

 

你可能感兴趣的:(Java8)