java8常用技能
·
目录
五、Java8 List<Map> 根据map对象某个字段值去重
示例:
List<Long> areaList = couponBaseExtraList
.stream().filter(entity -> entity.getAreaId() != null)
.map(CouponBaseExtraEntity :: getAreaId)
.collect(Collectors.toList());
初次看一脸懵逼
1、箭头函数
一、案例1:取List<Map>中其中一个元素,组成新List对象
List<Map> partnerList = …………;
List<Long> userIdList = partnerList.stream().map(partner -> (Long)partner.get("userId")).collect(Collectors.toList());
扩展:取对象某字段,合并转为逗号分隔字符串
String userIdList = partnerList.stream().map(partner -> partner.get("userId").toString()).collect(Collectors.joining(","));
扩展:list每个元素截取字符串(或正则),组装成新list,然后set去重
list<Integer> areaList = new ArrayList<>{110000,120023,113098};
//截取字符串,组装成新list
List<String> provincePrefixs = areaList.stream().map(info -> (info+"").substring(0,2)).collect(Collectors.toList());
//set去重
Set<String> provincePrefix = new HashSet<>(provincePrefixs);
//循环所有区域取出数据;
JSONArray areaAllList = [{code: "110000", level: 1, name: "北京市", id: 110000, parentId: -1},{code: "110100", level: 2, name: "市辖区", id: 110100, parentId: 110000}];
//筛选满足条件的区域
List areaOwnList = areaAllList.stream().filter(info -> provincePrefix.contains(((Map)info).get("code").toString().substring(0,2))).collect(Collectors.toList());
额外补充:list转数组
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
String[] strings = list.toArray(new String[list.size()]);
二、取JSONArray某字段,组成list
JSONArray deviceArray = deviceObj.getJSONObject("data").getJSONArray("list");
List<String> codeList = null;
if (deviceArray!= null && deviceArray.size()>0){
codeList = deviceArray.stream().map(device -> ((JSONObject) device).getString("deviceId")).collect(Collectors.toList());
}
三、list转map
/**
* List -> Map
* 需要注意的是:
* 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));
简单方式(key-value的形式):
Map<Long, String> userMap = listUser.stream().collect(Collectors.toMap(UserEntity::getId, UserEntity::getRealName));
额外:List<String>转Map<String, String>
Map<String, String> map = list.stream().collect(Collectors.toMap(item->item,String::toString));
四、list<Map>按某元素排序
//按超时订单数量,倒叙
cabinList = cabinList.stream().sorted(((o1, o2) -> (Integer) o2.get("overCount") - (Integer) o1.get("overCount")))
.collect(Collectors.toList());
persions.sort((t1,t2)->{
if(t1.getAge() > t2.getAge()){
return -1;
}
return 1;
});
问题:
1、stream().collect()处理空对象问题;
如果对象为null,则报NullPointerException
如果对象不为null,size为0,处理则不报错;
五、Java8 List<Map> 根据map对象某个字段值去重
思路:
1、将list转为map(通过key去重)
2、然后调用values(),把map转为list;
//数据库查List
List<AuditCorpConfOrderAllocationEntity> list = this.service.find(form.getQuery(), null);
//去重corpId
list = (List<AuditCorpConfOrderAllocationEntity>) list.stream().collect(Collectors.toMap(AuditCorpConfOrderAllocationEntity::getCorpId, Function.identity(), (oldObj, newObj) -> oldObj)).values();
六、java8分组、统计
原理:通过分组字段,拆分为多个list;
//原list
List<Product> prodList = Lists.newArrayList(prod1, prod2, prod3);
//通过分组字段,拆分为多个list
Map<String, List<Product>> prodMap= prodList.stream().
collect(Collectors.groupingBy(Product::getCategory));
七、optional判空(级联对象空指针)
private static void compare() throws Throwable {
Address address = new Address();
address.setCity("wuhan");
Teacher1 teacher1 = new Teacher1();
teacher1.setTName("qsm老师");
teacher1.setAddress(address);
//原来的级联判空
if (ObjectUtils.isNotEmpty(teacher1) && ObjectUtils.isNotEmpty(teacher1.getAddress())) {
System.out.println(teacher1.getAddress().getCity());//wuhan
}
//使用Optional
//下面为简写,与上面一致
Optional.ofNullable(teacher1).map(Teacher1::getAddress).map(Address::getCity).orElse(null);//wuhan
//Optional.ofNullable(teacher1).map(tempTeacher -> tempTeacher.getAddress()).map(tempAddress -> tempAddress.getCity()).orElse(null);
//若程序中某个字段必须非空,否则需要抛出异常
//原来方法
if (ObjectUtils.isEmpty(teacher1) || ObjectUtils.isEmpty(teacher1.getAddress()) || ObjectUtils.isEmpty(teacher1.getAddress().getProvince())) {
throw new BizException("32", "省份不存在");
}
Optional.ofNullable(teacher1).map(Teacher1::getAddress).map(Address::getProvince).orElseThrow(() -> new BizException("32", "省份不存在"));
//com.jd.ins.qsm.demo.web.commom.excption.BizException: 省份不存在
}
八、Comparator.comparing比较排序
//默认升序[reversed()为倒叙]
list.sort(Comparator.comparing(User::getAge).reversed());
list.forEach(System.out::println);
更多推荐
已为社区贡献5条内容
所有评论(0)