Lambda表示式經典應用場景

2021-10-23 22:49:22 字數 2816 閱讀 1687

1.取出list中的所有收付款流水的最大/最小建立時間

// fmdebitcreditpayreceivelist  最小建立時間收付款流水

fmdebitcreditpayreceivelist fmdebitcreditpayreceivelist = null;

optionaloptional = fmpayreceivelistpageinfo.getlist()

.stream().filter(objects::nonnull)

.filter(x -> x != null && x.getcreatetime() != null)

.sorted(comparator.comparing(fmdebitcreditpayreceivelist::getcreatetime))

.findfirst();

fmdebitcreditpayreceivelist = optional.ispresent() ? optional.get() : new fmdebitcreditpayreceivelist();

// 這裡注意一下optional必須先呼叫ispresent()方法之後才能呼叫get()方法

想要獲取最大建立時間收付款流水的話,加上reversed倒排序即可

.sorted(comparator.comparing(fmdebitcreditpayreceivelist::getcreatetime)

.reversed)

2.獲取list中的某一列的值

獲取銷售訂單list中實體的所有訂單編號

listcodelist = saleorderlist.stream().map(saleorderentity::getordercode)

.collect(collectors.tolist()));

3.獲取list中經過篩選後按照某個條件分組的map

// 篩選出所有amount_type(代收代付型別)的銷售訂單並按照計費方式分組

map> saleordermap = saleorderlist.stream()

.filter(x -> amount_type.equals(x.gettype()))

.collect(collectors.groupingby(saleorderentity::getpricingtype));

// map中有乙個好用的防空的方法, 獲取map中對應code的值,沒有的就預設0l

saleordermap.getordefault(saleorderentity.getcode, 0l);

4.lambda表示式list構造map

// 構造乙個鍵是訂單編號,值是實提重量的map

mapordermap = saleorderentitylist.stream()

.collect(collectors.tomap(saleorderentity::getordercode,

saleorderentity::getsumdeliveryqtty));

5.彙總list某個的數字

bigdecimal totalamount = saleorderentitylist.stream()

.map(saleorderentity::getamount)

.reduce(bigdecimal.zero, bigdecimal::add)

6.list的foreach()方法

param(引數):(consumer<? super t> action)函式式介面

單個引數無返回值

@functionalinte***ce

public inte***ce consumer

應用例項:

listfminterestrules = fminterestruleservice.getfminterestrulebyrelationid(presellid);

listfminterestrulevos = new arraylist<>();

fminterestrules.foreach(x -> );

7.map的foreach()方法

param(引數):(biconsumer<? super k, ? super v> action)  函式式介面

兩個引數無返回值

@functionalinte***ce

public inte***ce biconsumer

應用例項:

functionf = x ->  instant.ofepochmilli(x.getinteresttime()).atzone(zoneid.systemdefault()).tolocaldate().format(datetimeformatter.ofpattern("yyyy-mm"));; 

map> collect = interestlist.stream().collect(collectors.groupingby(f));

listretlist = new arraylist<>(collect.size());

collect.foreach((k, contractinterestlist) -> );

Lambda表示式使用場景及例項

集合排序 已知在乙個arraylist中有若干個person物件,將這些person物件按照年齡降序排序。public class exercise1 treeset排序 public class exercise2 else set.add newperson aaa 10 set.add new...

lambda表示式 lambda表示式

1.概述 c 11 中的 lambda 表示式用於定義並建立匿名的函式物件,以簡化程式設計工作。lambda 的語法形式如下 函式物件引數 操作符過載函式引數 mutable 或 exception 宣告 返回值型別可以看到,lambda 主要分為五個部分 函式物件引數 操作符過載函式引數 muta...

Lambda表示式的應用

在lambda表示式中可以當成乙個變數來使用,然後傳入到方法的引數中.要建立 lambda 表示式,要在 的左側寫引數,然後在另一側寫表示式。delegate int del int i static void lin stringargs intmytry lizi.jiamytry m m 2 ...