日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > java >内容正文

java

java 8 lambda sort_Java8 用Lambda表达式给List集合排序的实现|chu

發(fā)布時間:2024/8/5 java 50 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java 8 lambda sort_Java8 用Lambda表达式给List集合排序的实现|chu 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Lambda用到了JDK8自帶的一個函數(shù)式接口Comparator。

準(zhǔn)備一個Apple類

public class Apple { private int weight; private String color; public Apple(){} public Apple(int weight) { this.weight = weight; } public Apple(int weight, String color) { this.weight = weight; this.color = color; } setters();getters();toString(); }

步驟一:

public class AppleComparator implements Comparator { @Override public int compare(Apple o1, Apple o2) { return o1.getWeight() - o2.getWeight(); } }

步驟二:準(zhǔn)備一個List集合

ArrayList inventory = Lists.newArrayList( new Apple(10, "red"), new Apple(5, "red"), new Apple(1, "green"), new Apple(15, "green"), new Apple(2, "red"));

步驟三:順序排序,三種方式

/** * 順序排序 */ // 1、傳遞代碼,函數(shù)式編程 inventory.sort(new AppleComparator()); System.out.println(inventory); // 2、匿名內(nèi)部類 inventory.sort(new Comparator() { @Override public int compare(Apple o1, Apple o2) { return o1.getWeight() - o2.getWeight(); } }); // 3、使用Lambda表達(dá)式 inventory.sort((a, b) -> a.getWeight() - b.getWeight()); // 4、使用Comparator的comparing Comparator comparing = comparing((Apple a) -> a.getWeight()); inventory.sort(comparing((Apple a) -> a.getWeight())); //或者等價于 inventory.sort(comparing(Apple::getWeight));

步驟四:逆序排序

/** * 逆序排序 */ // 1、 根據(jù)重量逆序排序 inventory.sort(comparing(Apple::getWeight).reversed());

步驟五:如果兩個蘋果一樣重,就得再找一個條件來進(jìn)行排序

// 2、如果兩個蘋果的重量一樣重,怎么辦?那就再找一個條件進(jìn)行排序唄 inventory.sort(comparing(Apple::getWeight).reversed().thenComparing(Apple::getColor));

參考:

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持華域聯(lián)盟。

總結(jié)

以上是生活随笔為你收集整理的java 8 lambda sort_Java8 用Lambda表达式给List集合排序的实现|chu的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。