Java8 List&Map操作 stream ,filter ,map,forEach等功能

List<Apple> appleList = new ArrayList<>();//存放apple对象集合
Apple apple1 =  new Apple(1,"苹果1",new BigDecimal("3.25"),10);
Apple apple12 = new Apple(1,"苹果2",new BigDecimal("1.35"),20);
Apple apple2 =  new Apple(2,"香蕉",new BigDecimal("2.89"),30);
Apple apple3 =  new Apple(3,"荔枝",new BigDecimal("9.99"),40);
appleList.add(apple1);
appleList.add(apple12);
appleList.add(apple2);
appleList.add(apple3);

1、在List<Apple>中,查找name为苹果1的对象Apple

Optional<Apple> firstA = appleList .stream().filter(a -> "苹果1".equals(a.getName())).findFirst();


2、在List<Apple>中,查找name为苹果1的集合对象。

List<Apple> tmpList = appleList .stream().filter(a -> "苹果1".equals(a.getName())).collect(Collectors.toList());

3、在List<Apple>中,筛选出所有对象的name属性的集合对象。

List< String> tmpList = appleList .stream().map(Apple::getName).collect(toList());
4、List<String>转换成带逗号的字符串  str = "a, b, c"
commons-lang3-3.3.2.jar org.apache.commons.lang3.StringUtils.join(applyNameList, ",");
5、字符串 str =  "a, b, c"转换成List<String>
String str = "a, b, c";
List<String> result = Arrays.asList(StringUtils.split(str,","));  

6、List转Map  id为key,apple对象为value

/**
 * 需要注意的是:
 * toMap 如果集合对象有重复的key,会报错Duplicate key ....
 *  apple1,apple12的id都为1。
 *  可以用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2
 */
Map<Integer, Apple> appleMap = appleList.stream().collect(Collectors.toMap(Apple::getId, a -> a,(k1,k2)->k1));
7、分组  List里面的对象元素,以某个属性来分组,例如,以id分组,将id相同的放在一起

  //List 以ID分组 Map<Integer,List<Apple>>
Map<Integer, List<Apple>> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));

System.err.println("groupBy:"+groupBy);
{1=[Apple{id=1, name='苹果1', money=3.25, num=10}, Apple{id=1, name='苹果2', money=1.35, num=20}], 2=[Apple{id=2, name='香蕉', money=2.89, num=30}], 3=[Apple{id=3, name='荔枝', money=9.99, num=40}]}
8、求和  将集合中的数据按照某个属性求和

  BigDecimal:
//计算 总金额
BigDecimal totalMoney = appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
System.err.println("totalMoney:"+totalMoney);  //totalMoney:17.48
//计算 数量
int sum = appleList.stream().mapToInt(Apple::getNum).sum();
System.err.println("sum:"+sum);  //sum:100

示例,domain

public class Plan {
    private int id;    
    private String planNo;    
    private BigDecimal price;    
    private long total;    
    private State state;    
    private Calendar createTime;    
    private JSONObject features = new JSONObject();

Sate :noPay(1,"未支付"),     pay(2,"支付"),      settle(3,"结算"),

List<Plan>  planList = initList();

1. 把方案编号planNo转换大写 返回列表

List<String> noList = planList.stream().map(p->p.getPlanNo().toUpperCase()).collect(Collectors.toList());

2,价格由高到低排序

List<Plan> list = planList.stream().sorted((a,b) -> b.getPrice().compareTo(a.getPrice())).collect(Collectors.toList());

3,状态为支付的价格由高到低排序

planList.stream().filter(s -> State.pay == s.getState()).sorted((a,b) -> b.getPrice().compareTo(a.getPrice())).collect(Collectors.toList());

4,求最高价/最低价/总价,   total数量平均,总和

BigDecimal max = planList.stream().max((a,b)->a.getPrice().compareTo(b.getPrice())).get().getPrice();
BigDecimal min = planList.stream().min((a,b)->a.getPrice().compareTo(b.getPrice())).get().getPrice();
BigDecimal total = planList.stream().map(p->p.getPrice()).reduce(BigDecimal.ZERO,(a,b)->a.add(b));

平均 : planList.stream().mapToLong(Plan::getTotal).average().getAsDouble();

总和:planList.stream().mapToLong(Plan::getTotal).sum()

5,总共有多少种状态值

long count = planList.stream().map(p->p.getState()).distinct().count();
long c2 = planList.stream().map(p->p.getState()).collect(Collectors.toSet()).size();

6,方案编号中包含某些字符

List<Plan> list = planList.stream().filter(p->p.getPlanNo().contains("gt")).collect(Collectors.toList());

7,价格前三的方案

List<Plan> topList = planList.stream().sorted((a,b)->b.getPrice().compareTo(a.getPrice())).limit(3).collect(Collectors.toList());

8,按方案状态分组列表

Map<State, List<Plan>> map = planList.stream().collect(Collectors.groupingBy(p->p.getState()));

9,方案分成是否支付二种,查询列表

Map<Boolean, List<Plan>> map = planList.stream().collect(Collectors.partitioningBy(s -> s.getState()==State.noPay));

map.get(true) 是全部 未支付

map.get(false) 是支付 和 结算

10,转换成Map结构 <方案编号 ,  价格>

Map<String, BigDecimal> map = planList.stream().collect(Collectors.toMap(p->p.getPlanNo(), Plan::getPrice));

11,转换数据结构 ,  list转成数组  

Plan[] ps = planList.stream().toArray(Plan[]::new);

12,按状态算数量的总和/平均数

平均:Map<State, Double> map = planList.stream().collect(Collectors.groupingBy(Plan::getState, Collectors.averagingLong(Plan::getTotal)));

求和:Map<State, Long> sum = planList.stream().collect(Collectors.groupingBy(Plan::getState, Collectors.summingLong(Plan::getTotal)));

13、按状态统计BigDecimal

MAp<State,BigDecimal> map = planList.stream().collect(Collectors.groupingBy(Plan::getState, Collectors.maping(Plan::getPrice,Collectors.reducing(BigDecimal.ZERO,BigDecimal::add))));

Map<State, LongSummaryStatistics> sumMap =  planList.stream().collect(Collectors.groupingBy(Plan::getState, Collectors.summarizingLong(Plan::getTotal)));

LongSummaryStatistics描述流中元素的各种摘要数据,求 count, min, max, sum, and average.

14、分组后计数

Map<String, Long> groupByType = intentionList.stream().filter(a -> Func.isNotEmpty(a.getMerchantType())).collect(Collectors.groupingBy(IntentionVO::getMerchantType, Collectors.counting()));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值