Java在8后引入了lambda表达式和流,使得排序方法有了变化
class User { int id; String name; public User(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public String getName() { return name; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + '}'; }}List<String> words = Arrays.asList("566ggg", "ce", "ddd", "dc", "cds", "cece"); //使用list的sort方法 words.sort(Comparator.comparingInt(String::length).thenComparing((String.CASE_INSENSITIVE_ORDER))); System.out.println(words); //使用Collections工具类 三种方法等价 Collections.sort(words, (s1, s2) -> Integer.compare(s1.length(), s2.length())); Collections.sort(words, Comparator.comparing(word -> word.length())); Collections.sort(words, new Comparator<String>() { public int compare(String s1, String s2) { return Integer.compare(s1.length(), s2.length()); } }); System.out.println(words); List<User> userList = new ArrayList<>(); userList.add(new User(45, "lili")); userList.add(new User(45, "abcd")); userList.add(new User(41, "bbde")); userList.add(new User(43, "cdef")); userList.sort(Comparator.comparing(User::getId).thenComparing(User::getName)); System.out.println(userList);
输出结果:
[ce, dc, cds, ddd, cece, 566ggg][ce, dc, cds, ddd, cece, 566ggg][User{id=41, name='bbde'}, User{id=43, name='cdef'}, User{id=45, name='abcd'}, User{id=45, name='lili'}]
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦