Java8怎么用Lambda表達(dá)式給List集合排序

這篇文章主要介紹“Java8怎么用Lambda表達(dá)式給List集合排序”,在日常操作中,相信很多人在Java8怎么用Lambda表達(dá)式給List集合排序問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”Java8怎么用Lambda表達(dá)式給List集合排序”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!

創(chuàng)新互聯(lián)公司堅持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:網(wǎng)站設(shè)計制作、網(wǎng)站建設(shè)、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時代的君山網(wǎng)站設(shè)計、移動媒體設(shè)計的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!

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

準(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<Apple> {  @Override  public int compare(Apple o1, Apple o2) {    return o1.getWeight() - o2.getWeight();  }}

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

ArrayList<Apple> 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<Apple>() {  @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的comparingComparator<Apple> 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));

到此,關(guān)于“Java8怎么用Lambda表達(dá)式給List集合排序”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

當(dāng)前標(biāo)題:Java8怎么用Lambda表達(dá)式給List集合排序
鏈接分享:http://muchs.cn/article40/ihjjho.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供關(guān)鍵詞優(yōu)化企業(yè)網(wǎng)站制作、網(wǎng)頁設(shè)計公司、小程序開發(fā)網(wǎng)站營銷、網(wǎng)站維護(hù)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)頁設(shè)計公司