- 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);
}
}
- 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;
}
}