JAVA8新特性笔记

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")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值