1、数组中每个元素除以3并打印结果
Arrays.asList(new Integer[]{0,1,2,3,4,5,6,7,8,9}).stream().map((n)->n/3).forEach(System.out::println);
2、获取对象列表中某个元素并去除空值,最后合并为list
List<Long> areaIds = userLoginLogList.stream().map(UserLoginLogStatisticsVO::getAreaId).filter(x -> x != null).collect(Collectors.toList());
3、java8新特性之逗号分隔字符串转List<Long>
业务背景:
某个数据库字段,存储的是逗号分隔的id,可能是Integer也可能是Long型的,比如:1,2,3等;需要转换成Long型的List或者Integer型的List,怎么做更简便??
见代码:
//You can use the Lambda functions of Java 8 to achieve this without looping
//来自:http://stackoverflow.com/questions/19946980/convert-string-to-listlong
String ids= "1,2,3,4,5,6";
List<Long> listIds = Arrays.asList(ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
System.out.println(Arrays.toString(listIds .toArray()));//[1,2,3,3,4,5,6]
4、循环打印list中的对象
list.stream().forEach(u->{System.out.println(u.getId());});
5、根据两个list中的属性去除重复
List<User> users = new ArrayList<>();
User user = new User();
user.setUserName("张三");
user.setId(1111L);
users.add(user);
List<User> users1 = new ArrayList<>();
User user1 = new User();
user1.setUserName("张三");
user1.setId(1111L);
users1.add(user1);
users1.addAll(users);
Set<User> userSet = new TreeSet<>((o1, o2) -> o1.getId().compareTo(o2.getId()));
userSet.addAll(users1);
userSet.stream().forEach(u->{System.out.println(u.getId());});
List<User> setList = new ArrayList<User>(userSet);
setList.stream().forEach(u->{System.out.println(u.getId());});