关于Stream流的一些常用方法

发布时间 2023-07-08 11:37:13作者: it-小林

前言

  在这里先说明一下,这个重在应用,本文就不对概念跟描述做过多赘述。

应用

1)提取对象数组中的某一个字段(带去重)

List<String> orderIdList = orderList.stream().map(e -> e.getOrderId()).distinct().collect(Collectors.toList());//收集全部orderId
Set thirdCategoryIdSet = thirdCategoryNoList.stream().collect(Collectors.toSet());

 

2)将List转为map

这里分多种,

value为List

Map<String, List<ShopItem>> itemIdMap = itemList.stream().collect(Collectors.groupingBy(ShopItem::getCItemId));

value为对象

Map<String, ShopItem> map = itemList.stream().collect(Collectors.toMap(a -> a.getItemId(), a -> a, (k1, k2) -> k1));

value 为对象的一个字段

Map<String, String> map = itemList.stream().collect(Collectors.toMap(ShopItem::getItemId, ShopItem::getItemName));

 

3)获取列表的某一个元素进行拼接,指定符号分割

String remarks = itemList.stream().map(ShopItem::getItem).collect(Collectors.joining(";"));

 

4)分页获取列表

List<ShopItem> list = itemList.stream().skip(pageSize * (i - 1)).limit(pageSize).collect(Collectors.toList());

注意 要提前算好分页,免得超过数组下标