上海網(wǎng)站建設(shè)公司四葉互聯(lián)網(wǎng)站運營工作的基本內(nèi)容
背景
在java8中引入了Lambda表達式。其實,他就是一個匿名函數(shù)。我們經(jīng)常會用到一些循環(huán)遍歷,起始完全就可以通過Lambda來簡化我們不必要的操作,下面我們來看一下Lambda常用的方法。
準(zhǔn)備條件
@Data@Builderprivate static class Person {private Integer id;private String name;}
1、取List中某個值組成新的List或者Set
這個例子會用到我們Lambda中的map
語法:
List<Integer> result = list.stream().map(Persion::getId).collect(Collectors.toList());
Set<Integer> result = list.stream().map(Persion::getId).collect(Collectors.toSet());
2、取List中的兩個值作為map(健不能重復(fù)且不能為null)
語法:
Map<Integer, String> stringMap = list.stream().collect(Collectors.toMap(Persion::getId, Persion::getName));
3、groupBy的操作
語法:
Map<String, List<Person>> stringListMap = list.stream().collect(Collectors.groupingBy(Person::getName));
4、取兩個List集合的交集
語法:
List<Integer> intersect = listA .stream() .filter(a -> listB.stream().anyMatch(b -> Objects.equals(a, b))) .collect(Collectors.toList());
5、取兩個List集合的差集
語法:
List<Integer> intersect1 = listA .stream() .filter(a -> listB.stream().noneMatch(b -> Objects.equals(a, b))) .collect(Collectors.toList());
好了,今天關(guān)于Java8中Lambda表達式之Collection 的常見用法就到這里。
歡迎大家點擊下方卡片,關(guān)注《coder練習(xí)生》