Java 8的新特性

  1. lambda表达式详解
@FunctionalInterface
interface MyFunInterface {
    int test(String s);
}
public class MyTest {
   public static void main(String[] args) {

       //Integer.valueOf()相当抽象方法的实现的方法体,将结果返回,该方法实现将字符串参数2018转成int类型并返回
       MyFunInterface intValConvertor=from->Integer.valueOf(from);
       int intVal = intValConvertor.test("2018");
       //1.上面个lambda可以用:引用类方法简化
       MyFunInterface intValConvertor1=Integer::valueOf;
       intVal=intValConvertor1.test("2018");
       System.out.println(intVal);
       }
}
  1. Stream(流)
/**
 * Created by SqMax on 2018/6/13.
 */
public class MyTest1 {
    public static void main(String[] args) {
        List<People> peopleList=new ArrayList<>();
        peopleList.add(new People("sun","male",23,8000.0));
        peopleList.add(new People("li","female",21,7600.1));
        peopleList.add(new People("wang", "male", 32, 9000));
        peopleList.add(new People("fan","female",18,5000));

        //将姓名收集到一个list
        List<String> nameList = peopleList.stream().map(People::getName).collect(Collectors.toList());

        //将姓名收集到一个set
        Set<String> nameSet=peopleList.stream().map(People::getName).collect(Collectors.toSet());

        //将姓名以逗号为分隔符连接
        String nameJoined = peopleList.stream().map(People::getName).collect(Collectors.joining(", "));

        //计算总年龄
        int totalAge=peopleList.stream().collect(Collectors.summingInt(People::getAge));

        //以性别对人员分组
        Map<String, List<People>> bySex = peopleList.stream().collect(Collectors.groupingBy(People::getSex));

        //计算各性别的总薪水
        Map<String,Double> totalBySex=peopleList.stream().collect(Collectors.groupingBy(People::getSex,
                Collectors.summingDouble(People::getSalary)));

        //以6000薪水分割线对人员分组
        Map<Boolean, List<People>> pass6000 = peopleList.stream().collect(Collectors.partitioningBy(people -> people.getSalary() > 6000));

    }

}
class People{
    private String name;
    private String sex;
    private int age;
    private double salary;

    public People(String name, String sex, int age, double salary) {
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值