应了那句老话“好记性不如烂笔头”,所以写了这篇关于Java常用写法的代码。
1.根据某条件对List进行分组
Map<Long, List<GetMenuExtGroupBean>> groupListMap = groupList.stream().collect(groupingBy(GetMenuExtGroupBean::getGroupId));
上面的写法,分组后原来的顺序就被打乱了,所以要使用下面的方法,具体为什么顺序会乱,大家可以看下底层的接口,也可以参考这篇博客(java8 小技巧保证分组groupingBy后排序不变_groupingby排序_双斜杠少年的博客-优快云博客)。
LinkedHashMap<Long, List<GetMenuExtGroupBean>> groupListMap = groupList.stream().sorted( Comparator.comparingDouble(GetMenuExtGroupBean::getMenuId)).collect(Collectors.groupingBy(GetMenuExtGroupBean::getGroupId, LinkedHashMap::new, Collectors.toList()));
2.获取List集合中某字段的集合
List<Long> groupMenuIds = getMenuExtGroupBeans.stream().map(GetMenuExtGroupBean::getMenuId).collect(Collectors.toList());
3.判断两个List<Long>集合中是否有相同数据
Collections.disjoint(menuIds, groupMenuIds)
返回false,表示有,返回true,表示没有相同元素数据
4.字符串分割后转成其他类型的数组
Arrays.stream(userProductId.split(",")).map(Long::new).collect(Collectors.toList())
5.移除数组中不符合某些条件的数据
list.removeIf(e -> "张三".equals(e.getName()));
移除了数组中名字为“张三”的数据
6.匹配数组中是否有符某些合条件的数据
boolean b = list.stream().anyMatch(p -> p.getId().compareTo(vo.getId())==0);
7.数据去重
ids.stream().distinct().collect(Collectors.toList())
8.map循环
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "hello");
map.put(2, "bit");
map.put(3, "hello");
map.put(4, "lambda");
map.forEach((k,v)->{
System.out.println(String.format("k:%s,v:%s",k,v));
});
9.通过某属性对List<JavaBean>去重
List<JavaBean> list = ... // 原始List<JavaBean>
List<JavaBean> distinctList = list.stream()
.collect(Collectors.groupingBy(JavaBean::getId))
.values()
.stream()
.map(group -> group.get(0))
.collect(Collectors.toList());
// distinctList即为根据id去重后的List<JavaBean>