1.filter流過濾
List<UcShopCourseBizPojo> shopCourseLists = ucShopCourseBizPojoList.parallelStream()
.filter(a -> a.getDistan().compareTo(new BigDecimal("5000")) == -1)
.collect(Collectors.toList());
將list轉換成併發流,使用filter過濾list裏的距離小於5千米的數據。
collect將流生成新的list,既過濾後的list。
2.collectingAndThen 過濾對象重複的某個屬性
//一個門店只顯示一個課程
List<UcShopCourseBizPojo> sLists = shopCourseLists.stream().collect(
Collectors.collectingAndThen(Collectors.toCollection(
() -> new TreeSet<>(Comparator.comparing(c -> c.getShopId()))), ArrayList::new)
);
過濾UcShopCourseBizPojo對象裏 shopId相同的對象,但是這樣返回的過濾結果每回都不是一定的。
3.limit.sorted()排序獲取限制的幾個
List<UcShopCourseBizPojo> collect = sLists.parallelStream().sorted(Comparator.comparing(UcShopCourseBizPojo::getDistan))
.limit(15).collect(Collectors.toList());
sorted裏使用Comparator比較器進行比較 並獲取排序後最上面的15個數據。
collect = sLists.stream().sorted(Comparator.comparing(UcShopCourseBizPojo::getId).reversed()).limit(4).collect(Collectors.toList());
reversed做一些反轉。
3.list.map()生成新的list
List<McCouponFrontBizPojo> list = c.getMcCouponFrontBizPojos();
List<McCouponCouponType> couponTypes = list.stream().map(McCouponFrontBizPojo::getCouponType).
collect(Collectors.toList());
list先stream流化,再使用map獲取 McCouponFrontBizPojo對象裏的getCouponType屬性,生成新的list
4.遍歷map
/**
* 遍歷Map第五種
* 通過k,v遍歷,Java8獨有的
*/
@Test
public void testFive() {
map.forEach((k, v) -> {System.out.println("key:value = " + k + ":" + v);});
}
獲取map中的每一個key、value並打印。