Java8 Lambda表达式常见用法
貌似只是处理简单循环之类的稍微舒服一点
References:
- https://www.ibm.com/developerworks/cn/java/j-lo-java8streamapi/index.html 一篇非常好的Stream API介绍文章
下面贴一些日常使用的小例子:
将Enum中的变量抽取成List,并排序和去重:
public enum PhoneCountryCode { ... ,ZW("ZW","263") ,CN("CN","86"); private String name; private String code; private PhoneCountryCode(String name,String code) { this.name = name; this.code = code; } public String getCode() { return code; } public String getName() { return name; } }
List<String> COUNTRY_CODE_LIST = Stream.of(PhoneCountryCode.values())
.map(PhoneCountryCode::getCode)
.sorted((c1, c2) -> {
// 按照长度和ASCII降序排
if (c1.length() != c2.length()) {
return c2.length() - c1.length();
}
return c2.compareTo(c1);
})
.distinct()
.collect(Collectors.toList());
将List
中的Account提取为一个List ,并去重。 List<AccountInfo> infoList = ...; List<String> list = infoList.stream() .map(AccountInfo::getAccount) .distinct() .collect(Collectors.toList());
将List
转换为Map,key为AccountInfo的number变量,value为AccountInfo对象。 List<AccountInfo> infoList = ...; Map<String, AccountInfo> collect = infoList.stream() .collect(Collectors.toMap(AccountInfo::getNumber, Function.identity()));
将List
转换为List ,并将AccountInfo的accountNumber和currency复制到新的List中。 List<AccountDTO> accountDTOList = accountInfoList.stream() .map(accountInfo -> { AccountDTO accountDTO = new AccountDTO(); accountDTO.setAccountNumber(accountInfo.getAccountNumber()); accountDTO.setCurrency(accountInfo.getCurrency()); return accountDTO; }) .collect(Collectors.toList());