JAVA8新特性
创建固定数组
List list= Arrays.asList(“a”, “b”, “c”, “d”);
取出数组属性组成新数组
List idcards= users.stream().map(User::getIdcard).collect(Collectors.toList());
List collect =list.stream().map(String::toUpperCase).collect(Collectors.toList());
数组中所有元素都执行某种方法
List num = Arrays.asList(1,2,3,4,5);
List collect1 = num.stream().map(n -> n * 2).collect(Collectors.toList());
System.out.println(collect1); //[2, 4, 6, 8, 10];
获取父元素的所有子元素的所有子元素的…
deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
public TreeSelect(SysDept dept)
{
this.id = dept.getDeptId();
this.label = dept.getDeptName();
this.children = dept.getChildren().stream().map(TreeSelect::new).collect(Collectors.toList());
}
stream.filter一般适用于list集合,作用为按条件查询。
//在集合中查询用户名为huxiansen的集合
List<SysUser> userList = list.stream().filter(user -> "huxiansheng".equals(user.getNickName())).collect(Collectors.toList());
//在集合中查询出第一个用户密码为123456的用户
Optional<SysUser> user = list.stream().filter(userTemp -> "111111".equals(userTemp.getPassword())).findFirst();
Collectors.toList()可指定泛型
List<Emp> employees2 =employees.stream().filter(p->p.getAge()>21).collect(Collectors.<Emp>toList());
去重
List<String> finalList = list.stream().distinct().collect(Collectors.toList());
自然排序
list.stream().sorted(Comparator.comparing(Student::getAge));
逆序排序
list.stream().sorted(Comparator.comparing(Student::getAge).reversed());
并行流
stream().parallel()
parallelStream()
去掉符合条件的元素
dtoList.removeIf(item->item.getName().equals("admin"));
接口默认方法
解决了接口实现类必须实现接口全部方法的局限性
default void fangFa(){}
Optional
解决了判断为null并赋值
Optional.ofNullable(user).map(User::getUserName).orElse("Unknown")