Java8 用Lambda表達式給List集合排序的實現(xiàn)
Lambda用到了JDK8自帶的一個函數(shù)式接口Comparator<T>。
準備一個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();
}
}
步驟二:準備一個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表達式
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()));
//或者等價于
inventory.sort(comparing(Apple::getWeight));
步驟四:逆序排序
/** * 逆序排序 */ // 1、 根據(jù)重量逆序排序 inventory.sort(comparing(Apple::getWeight).reversed());
步驟五:如果兩個蘋果一樣重,就得再找一個條件來進行排序
// 2、如果兩個蘋果的重量一樣重,怎么辦?那就再找一個條件進行排序唄 inventory.sort(comparing(Apple::getWeight).reversed().thenComparing(Apple::getColor));
https://gitee.com/play-happy/base-project
參考:
【1】《Java8實戰(zhàn)》
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
redis.clients.jedis.exceptions.JedisMovedDataException異常解決
redis.clients.jedis.exceptions.JedisMovedDataException?異常是在使用?Jedis?客戶端與?Redis?集群進行交互時發(fā)生的,下面就來介紹一下解決方法,感興趣的可以了解一下2024-05-05
java數(shù)據(jù)結(jié)構(gòu)基礎(chǔ):順序隊列和循環(huán)隊列
下面小編就為大家分享一篇java隊列實現(xiàn)方法(順序隊列,循環(huán)隊列),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-08-08
java 使用ImageIO.writer從BufferedImage生成jpeg圖像遇到問題總結(jié)及解決
這篇文章主要介紹了java 使用ImageIO.writer從BufferedImage生成jpeg圖像遇到問題總結(jié)及解決的相關(guān)資料,需要的朋友可以參考下2017-03-03

