首页 > 基础资料 博客日记

Java中使用Lambda表达式对集合排序

2024-02-18 21:56:32基础资料围观339

Java资料网推荐Java中使用Lambda表达式对集合排序这篇文章给大家,欢迎收藏Java资料网享受知识的乐趣

一.利用lambda对list集合排序

先定义一个集合

List<Integer> list = new ArrayList<>();
list.add(1);
list.add(5);
list.add(4);
list.add(3);
list.add(7);

1.升序排序

list.sort((a,b)->a.compareTo(b));

list.sort(Comparator.comparing(a->a));

list.sort((a,b)->a-b);

// 2、匿名内部类
list.sort(new Comparator<Integer>() {
	@Override
	public int compare(Integer o1, Integer o2) {
		return o1-o2;
	}
});

2.降序排序

list.sort((a,b)->b-a);

匿名内部类方法

 list.sort(new Comparator<Integer>() {
      @Override
       public int compare(Integer o1, Integer o2) {
              return o2-o1;
       }
 });

对对象集合操作,其实与基本类型集合操作类似

List<User> list1 = new ArrayList<User>();
User user = new User("张三", "15", "男");
User user1 = new User("李四", "10", "男");
list1.add(user);
list1.add(user1);
//1、年龄升序
list1.sort((a,b) -> a.getAge().compareTo(b.getAge()));
//2、姓名降序排列
list1.sort(Comparator.comparing(User::getName).reversed());
//等价于 2
list1.sort(Comparator.comparing(a->((User)a).getAge()).reversed());
//3、先按性别排,如果年龄相同,再按年龄排序
list1.sort(Comparator.comparing(User::getSex).reversed().thenComparing(User::getAge));

对 JSONArray 排序

定义一个json数组 resultArray

JSONArray resultArray = new JSONArray();
JSONObject result = new JSONObject();
result.put("name","张三");
result.put("age","15");
result.put("data","201812130451");
resultArray.add(result);
//根据姓名的倒序排序
resultArray.sort(Comparator.comparing(obj -> ((JSONObject) obj).getString("name")).reversed());
//根据时间倒序排序
resultArray.sort(Comparator.comparing(obj -> ((JSONObject) obj).getData("data")).reversed());
//根据年龄升序排序
resultArray.sort(Comparator.comparing(obj -> ((JSONObject) obj).getInteger("age")));

注意:reversed()函数的意思是将数组颠倒。其用法常见于字符串处理中,将字符串颠倒
如:

String str = "abcd";
StringBuffer sb = new StringBuffer(str);
sb.reverse();
System.out.println(str);
System.out.println(sb.toString());

---------------------------------------
输出
abcd
dcba

二.java8-Lambda中比较器Comparator的使用

典型的比较器示例

Comparator<Developer> byName = new Comparator<Developer>() {
    @Override
    public int compare(Developer o1, Developer o2) {
        return o1.getName().compareTo(o2.getName());
    }
};

等价的Lambda的方式

Comparator<Developer> byName = (Developer o1, Developer o2)->o1.getName().compareTo(o2.getName());

不使用Lambda的排序

假如我们要通过Developer 对象的年龄进行排序,通常情况下我们使用Collections.sort,new个匿名Comparator 类,类似下面这种:

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class TestSorting {

    public static void main(String[] args) {

        List<Developer> listDevs = getDevelopers();

        System.out.println("Before Sort");
        for (Developer developer : listDevs) {
            System.out.println(developer);
        }

        //sort by age
        Collections.sort(listDevs, new Comparator<Developer>() {
            @Override
            public int compare(Developer o1, Developer o2) {
                return o1.getAge() - o2.getAge();
            }
        });

        System.out.println("After Sort");
        for (Developer developer : listDevs) {
            System.out.println(developer);
        }

    }

    private static List<Developer> getDevelopers() {

        List<Developer> result = new ArrayList<Developer>();

        result.add(new Developer("ricky", new BigDecimal("70000"), 33));
        result.add(new Developer("alvin", new BigDecimal("80000"), 20));
        result.add(new Developer("jason", new BigDecimal("100000"), 10));
        result.add(new Developer("iris", new BigDecimal("170000"), 55));

        return result;

    }

}

-----------------------------------------------------------------------------------------------------
输出结果:
Before Sort
Developer [name=ricky, salary=70000, age=33]
Developer [name=alvin, salary=80000, age=20]
Developer [name=jason, salary=100000, age=10]
Developer [name=iris, salary=170000, age=55]

After Sort
Developer [name=jason, salary=100000, age=10]
Developer [name=alvin, salary=80000, age=20]
Developer [name=ricky, salary=70000, age=33]
Developer [name=iris, salary=170000, age=55]

当比较规则发生变化时,你需要再次new个匿名Comparator 类:

    //sort by age
    Collections.sort(listDevs, new Comparator<Developer>() {
        @Override
        public int compare(Developer o1, Developer o2) {
            return o1.getAge() - o2.getAge();
        }
    });

    //sort by name
    Collections.sort(listDevs, new Comparator<Developer>() {
        @Override
        public int compare(Developer o1, Developer o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });

    //sort by salary
    Collections.sort(listDevs, new Comparator<Developer>() {
        @Override
        public int compare(Developer o1, Developer o2) {
            return o1.getSalary().compareTo(o2.getSalary());
        }
    });

这样也可以,不过你会不会觉得这样有点怪,因为其实不同的只有一行代码而已,但是却需要重复写很多代码?

通过Lambda进行排序

在java8中,List接口直接提供了排序方法, 所以你不需要使用Collections.sort

    //List.sort() since Java 8
    listDevs.sort(new Comparator<Developer>() {
        @Override
        public int compare(Developer o1, Developer o2) {
            return o2.getAge() - o1.getAge();
        }
    });

Lambda 示例


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class TestSorting {

    public static void main(String[] args) {

        List<Developer> listDevs = getDevelopers();

        System.out.println("Before Sort");
        for (Developer developer : listDevs) {
            System.out.println(developer);
        }

        System.out.println("After Sort");

        //lambda here!
        listDevs.sort((Developer o1, Developer o2)->o1.getAge()-o2.getAge());

        //java 8 only, lambda also, to print the List
        listDevs.forEach((developer)->System.out.println(developer));
    }

    private static List<Developer> getDevelopers() {

        List<Developer> result = new ArrayList<Developer>();

        result.add(new Developer("ricky", new BigDecimal("70000"), 33));
        result.add(new Developer("alvin", new BigDecimal("80000"), 20));
        result.add(new Developer("jason", new BigDecimal("100000"), 10));
        result.add(new Developer("iris", new BigDecimal("170000"), 55));

        return result;

    }

}
------------------------------------------------------------------------
输出结果:
Before Sort
Developer [name=ricky, salary=70000, age=33]
Developer [name=alvin, salary=80000, age=20]
Developer [name=jason, salary=100000, age=10]
Developer [name=iris, salary=170000, age=55]

After Sort
Developer [name=jason, salary=100000, age=10]
Developer [name=alvin, salary=80000, age=20]
Developer [name=ricky, salary=70000, age=33]
Developer [name=iris, salary=170000, age=55]

更多的Lambda例子

根据年龄

    //sort by age
    Collections.sort(listDevs, new Comparator<Developer>() {
        @Override
        public int compare(Developer o1, Developer o2) {
            return o1.getAge() - o2.getAge();
        }
    });

    //lambda
    listDevs.sort((Developer o1, Developer o2)->o1.getAge()-o2.getAge());

    //lambda, valid, parameter type is optional
    listDevs.sort((o1, o2)->o1.getAge()-o2.getAge());

根据名字

    //sort by name
    Collections.sort(listDevs, new Comparator<Developer>() {
        @Override
        public int compare(Developer o1, Developer o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });

    //lambda
    listDevs.sort((Developer o1, Developer o2)->o1.getName().compareTo(o2.getName()));

    //lambda
    listDevs.sort((o1, o2)->o1.getName().compareTo(o2.getName()));

根据薪水

    //sort by salary
    Collections.sort(listDevs, new Comparator<Developer>() {
        @Override
        public int compare(Developer o1, Developer o2) {
            return o1.getSalary().compareTo(o2.getSalary());
        }
    });

    //lambda
    listDevs.sort((Developer o1, Developer o2)->o1.getSalary().compareTo(o2.getSalary()));

    //lambda
    listDevs.sort((o1, o2)->o1.getSalary().compareTo(o2.getSalary()))

倒序
正常排序

Comparator<Developer> salaryComparator = (o1, o2)->o1.getSalary().compareTo(o2.getSalary());
listDevs.sort(salaryComparator);

倒序

Comparator<Developer> salaryComparator = (o1, o2)->o1.getSalary().compareTo(o2.getSalary());
listDevs.sort(salaryComparator.reversed());

参考文章侵删:
java 使用Lambda对集合排序
java8-Lambda中比较器Comparator的使用


文章来源:https://blog.csdn.net/mfysss/article/details/131208592
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐

标签云