最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java8 用Lambda表達(dá)式給List集合排序的實(shí)現(xiàn)

 更新時(shí)間:2019年08月06日 11:30:12   作者:尋找風(fēng)口的豬  
這篇文章主要介紹了Java8 用Lambda表達(dá)式給List集合排序的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

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

準(zhǔn)備一個(gè)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)備一個(gè)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的comparing
Comparator<Apple> comparing = comparing((Apple a) -> a.getWeight());
inventory.sort(comparing((Apple a) -> a.getWeight()));
//或者等價(jià)于
inventory.sort(comparing(Apple::getWeight));

步驟四:逆序排序

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

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

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

https://gitee.com/play-happy/base-project

參考:

【1】《Java8實(shí)戰(zhàn)

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論

重庆市| 巨野县| 贵港市| 城固县| 麻江县| 峡江县| 湘潭市| 临邑县| 东乌| 新疆| 苗栗县| 灌南县| 宜兴市| 西藏| 乐陵市| 平和县| 普兰县| 克什克腾旗| 南昌县| 泾阳县| 嘉兴市| 疏附县| 涞水县| 孝昌县| 灌阳县| 修水县| 苏尼特左旗| 康定县| 库伦旗| 南平市| 克什克腾旗| 元阳县| 清水县| 静海县| 罗城| 华安县| 三河市| 宁陕县| 兴仁县| 辉南县| 西乡县|