Java lambda表达式 排序、分组、循环、截取

List 循环

list.forEach(map -> {
	//此处可以对map进行操作
});

根据【A属性的值】对List进行分组

//stream()方法不会改变原有tempList
Map<String, List<Map<String, Object>>> tempMap = tempList.stream().collect(Collectors.groupingBy(map -> MapUtils.getString(map, "A")));

List 转 Map

//stream()方法不会改变原有tempList,当key重复时,以最新的为准
Map<String, String> rowMap = tempList.stream().collect(Collectors.toMap(map1 -> MapUtils.getString(map1, "A"), map2 -> MapUtils.getString(map2, "B"), (key1, key2) -> key2));

//Function.identity()应用
List<Person> personList = new ArrayList<>();
Map<String, Person> collect = personList.stream().collect(Collectors.toMap(Person::getName, Function.identity()));

List 根据【A属性的值】 进行排序

//方法一:无stream()方法会对原有tempList进行改变
tempList.sort((Map<String, Object> m1, Map<String, Object> m2) -> MapUtils.getIntValue(m1, "A", 0) - MapUtils.getIntValue(m2, "A", 0));
//方法二:使用 Comparator.comparing 进行排序(map和实体)
tempList.sort(Comparator.comparingLong(m -> MapUtils.getLong(m, "A")));
//默认 升序
tempObject.sort(Comparator.comparing(Object::getA));
//降序
tempObject.sort(Comparator.comparing(Object::getA).reversed());
//其余方式参考:https://my.oschina.net/xinxingegeya/blog/2046405

获取List单列值

//stream()方法不会改变原有tempList
List<String> resultList = tempList.stream().map(map -> MapUtils.getString(map, "A")).collect(Collectors.toList());

List转Array

String[] tempArr= resultList.stream().toArray(String[]::new);
int[] tempArr = resultList.stream().mapToInt(p -> p.intValue()).toArray();
int[] tempArr = resultList.stream().mapToInt(Integer :: intValue).toArray();

List< String>去重

//List<String>进行去重
List<String> list = resultList.stream().distinct().collect(Collectors.toList());

List截取

List<String> list = resultList.stream().skip(start).limit(end).collect(Collectors.toList());
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值