java8到底有哪些特性
Lambda表達式
函數式接口
Stream
Optional
Predicate
Function
Consumer
Filter
Map-Reduce
新的Date API
1、Lambda 表達式簡介
Lambda 表達式是一種匿名函數(對 Java 而言這並不完全正確,但現在姑且這麼認爲),簡單地說,它是沒有聲明的方法,也即沒有訪問修飾符、返回值聲明和名字。
你可以將其想做一種速記,在你需要使用某個方法的地方寫上它。當某個方法只使用一次,而且定義很簡短,使用這種速記替代之尤其有效,這樣,你就不必在類中費力寫聲明與方法了。
2、Lambda 表達式的結構
讓我們瞭解一下 Lambda 表達式的結構。
- 一個 Lambda 表達式可以有零個或多個參數
- 參數的類型既可以明確聲明,也可以根據上下文來推斷。例如:(int a)與(a)效果相同
- 所有參數需包含在圓括號內,參數之間用逗號相隔。例如:(a, b) 或 (int a, int b) 或 (String a, int b, float c)
- 空圓括號代表參數集爲空。例如:() -> 42
- 當只有一個參數,且其類型可推導時,圓括號()可省略。例如:a -> return a*a
- Lambda 表達式的主體可包含零條或多條語句
- 如果 Lambda 表達式的主體只有一條語句,花括號{}可省略。匿名函數的返回類型與該主體表達式一致
- 如果 Lambda 表達式的主體包含一條以上語句,則表達式必須包含在花括號{}中(形成代碼塊)。匿名函數的返回類型與代碼塊的返回類型一致,若沒有返回則爲空
4、什麼是函數式接口
在 Java 中,Marker(標記)類型的接口是一種沒有方法或屬性聲明的接口,簡單地說,marker
接口是空接口。相似地,函數式接口是隻包含一個抽象方法聲明的接口。java.lang.Runnable 就是一種函數式接口,在 Runnable 接口中只聲明瞭一個方法 void
run(),相似地,ActionListener 接口也是一種函數式接口,我們使用匿名內部類來實例化函數式接口的對象,有了 Lambda
表達式,這一方式可以得到簡化。
1.List操作
//Java8 lambda遍歷list
items.forEach(c-> System.out.println(c));
items.forEach(item->{
if("C".equals(item)){
System.out.println(item);
}
});
System.out.println("--------");
//先過濾
items.stream().filter(s->s.contains("B")).forEach(c1-> System.out.println(c1));
2.Map操作
//Java8之前遍歷是這樣遍歷map
for(Map.Entry<String,Integer> entry:items.entrySet()){
System.out.println("key:" + entry.getKey() + " value:" + entry.getValue());
}
//Java8遍歷map
items.forEach((key,value)-> System.out.println("key:" + key + " value:" + value));
3.Groupingby操作
//分組
Map<String, List<Person>> collect = personList.stream().collect(Collectors.groupingBy(c -> c.getAddress()));
4.List轉換爲Map
//Java8 List轉換Map
Map<Integer,Person> map_ = personList.stream().collect(Collectors.toMap((key->key.getId()),(value->value)));
map_.forEach((key,value)-> System.out.println(key + ":" + value));
Map<Integer, Person> mappedMovies = personList.stream().collect(
Collectors.toMap(Person::getRank, Person::getData));
5.FilterMap操作
public static void main(String[] args) {
//before java iterator map
String result = null;
for(Map.Entry<Integer,String> entry:map_.entrySet()){
if("heroku.com".equals(entry.getValue())){
result = entry.getValue();
}
}
System.out.println("Before Java 8 :" + result);
//Java8 Map->Stream->Filter->String
result = map_.entrySet().stream().
filter(map->"heroku.com".equals(map.getValue()))
.map(map->map.getValue())
.collect(Collectors.joining());
System.out.println("Java 8 :" + result);
Map<Integer,String> collect = map_.entrySet().stream()
.filter(c->c.getKey()==2)
.collect(Collectors.toMap(p->p.getKey(),p->p.getValue()));
System.out.println(collect);
}
6.Optional操作可以防止NullPointException
Optional<String> optional = Optional.of("hello");
System.out.println(optional.isPresent());//true
System.out.println(optional.get());//hello
System.out.println(optional.orElse("false"));
optional.ifPresent((s)-> System.out.println(s.charAt(0)));//h
7.給出一個詳細的例子
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
private String name;
private int salary;
private String office;
}
public class ExampleEmployee {
private static List<Employee> employeeList = Lists.newArrayList();
static{
employeeList.add(Employee.builder().name("Matt").salary(5000).office("New York").build());
employeeList.add(Employee.builder().name("Steve").salary(6000).office("London").build());
employeeList.add(Employee.builder().name("Carrie").salary(20000).office("New York").build());
employeeList.add(Employee.builder().name("Peter").salary(7000).office("New York").build());
employeeList.add(Employee.builder().name("Pat").salary(8000).office("London").build());
employeeList.add(Employee.builder().name("Tammy").salary(29000).office("Shanghai").build());
}
public static void main(String[] args) {
//anyMatch
boolean isMatch = employeeList.stream().anyMatch(employee -> employee.getOffice().equals("London"));
System.out.println(isMatch);
//返回所有salary大於6000
boolean matched = employeeList.stream().allMatch(employee -> employee.getSalary()>4000);
System.out.println(matched);
//找出工資最高
Optional<Employee> hightestSalary = employeeList.stream().max((e1,e2)->Integer.compare(e1.getSalary(),e2.getSalary()));
System.out.println(hightestSalary);
//返回姓名列表
List<String> names = employeeList.stream().map(employee -> employee.getName()).collect(Collectors.toList());
System.out.println(names);
//List轉換成Map
Map<String,Employee> employeeMap = employeeList.stream().collect(Collectors.toMap((key->key.getName()),(value->value)));
employeeMap.forEach((key,value)-> System.out.println(key + "=" + value));
//統計辦公室是New York的個數
long officeCount = employeeList.stream().filter(employee -> employee.getOffice().equals("Shanghai")).count();
System.out.println(officeCount);
//List轉換爲Set
Set<String> officeSet = employeeList.stream().map(employee -> employee.getOffice()).distinct().collect(Collectors.toSet());
System.out.println(officeSet);
//查找辦公室地點是New York的員工
Optional<Employee> allMatchedEmployees = employeeList.stream().filter(employee -> employee.getOffice().equals("New York")).findAny();
System.out.println(allMatchedEmployees);
//按照工資的降序來列出員工信息
List<Employee> sortEmployeeList = employeeList.stream().sorted((e1,e2)->Integer.compare(e2.getSalary(),e1.getSalary())).collect(Collectors.toList());
//按照名字的升序列出員工信息
List<Employee> sortEmployeeByName = employeeList.stream().sorted((e1,e2)->e1.getName().compareTo(e2.getName())).collect(Collectors.toList());
System.out.println(sortEmployeeList);
System.out.println("按照名字的升序列出員工信息:" + sortEmployeeByName);
//獲取工資最高的前2條員工信息
List<Employee> top2EmployeeList= employeeList.stream()
.sorted((e1,e2)->Integer.compare(e2.getSalary(),e1.getSalary()))
.limit(2)
.collect(Collectors.toList());
System.out.println(top2EmployeeList);
//獲取平均工資
OptionalDouble averageSalary = employeeList.stream().mapToInt(employee->employee.getSalary()).average();
System.out.println("平均工資:" + averageSalary);
//查找New York
OptionalDouble averageSalaryByOffice = employeeList.stream().filter(employee -> employee.getOffice()
.equals("New York"))
.mapToInt(employee->employee.getSalary())
.average();
System.out.println("New York辦公室平均工資:" + averageSalaryByOffice);
}
}
8.Java8常見操作
public class EmployeeTest {
public static List<Employee> generateData() {
return Arrays.asList(new Employee("Matt", 5000, "New York"),
new Employee("Steve", 6000, "London"),
new Employee("Carrie", 10000, "New York"),
new Employee("Peter", 7000, "New York"),
new Employee("Alec", 6000, "London"),
new Employee("Sarah", 8000, "London"),
new Employee("Rebecca", 4000, "New York"),
new Employee("Pat", 20000, "New York"),
new Employee("Tammy", 9000, "New York"),
new Employee("Fred", 15000, "Tokyo"));
}
public static Map<String, Integer> generateMapData() {
Map<String, Integer> items = Maps.newHashMap();
items.put("A", 10);
items.put("B", 20);
items.put("C", 30);
items.put("D", 40);
items.put("E", 50);
items.put("F", 60);
return items;
}
@Test
public void testEmployee() {
List<Employee> results = generateData();
//打印出名字是Steve的員工信息
results.forEach(c -> {
if (c.getName().equals("Steve")) {
System.out.println(c);
}
});
System.out.println("---------");
//找出年薪超過6000的員工
results.stream().filter(c -> c.getSalary() >= 60000).forEach(c -> System.out.println(c));
System.out.println("--->>>>>>----");
//java8遍歷map
Map<String, Integer> map_ = generateMapData();
map_.forEach((key, value) -> System.out.println("key:" + key + "," + "value:" + value));
System.out.println("---->>>>分組>>>-----");
//java8 分組操作
Map<String, List<Employee>> groupMap = results.stream().collect(Collectors.groupingBy(c -> c.getOffice()));
System.out.println(groupMap);
System.out.println("---->>>>List轉化爲Map>>>----");
//List轉化Map
Map<String, Object> map = results.stream().collect(Collectors.toMap(Employee::getName, Employee::getOffice));
map.forEach((key, value) -> System.out.println("key:" + key + "," + "value:" + value));
System.out.println("---->>>>>>>----");
Map<Integer, Employee> employeeMap = results.stream().collect(Collectors.toMap((key -> key.getSalary()), (value -> value)));
employeeMap.forEach((key, value) -> System.out.println(key + "," + value));
System.out.println("---->>遍歷map>>>----");
//打印出值大於30的map
Map<String, Integer> resultMap = map_.entrySet().stream().filter(c -> c.getValue() > 30).collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
resultMap.forEach((key, value) -> System.out.println(key + "=" + value));
System.out.println(">>>>>>>>>>>>>>>");
//打印key=D的map
Map<String, Integer> mapResults = map_.entrySet().stream().filter(c -> c.getKey().equals("D")).collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
mapResults.forEach((key, value) -> System.out.println(key + ">>>>" + value));
System.out.println(">>>>>>>Optional>>>>>>>");
Optional<String> optional = Optional.of("hello");
System.out.println(optional.isPresent());
}
@Test
public void testEmployeeExample() {
//anyMatch
List<Employee> employeeList = generateData();
boolean isMatch = employeeList.stream().anyMatch(employee -> employee.getOffice().equals("London"));
System.out.println(isMatch);
//allMatch
boolean matched = employeeList.stream().allMatch(employee -> employee.getOffice().equals("London"));
System.out.println(matched);
//找出工資最高的
Optional<Employee> employeeOptional = employeeList.stream().max((e1,e2)->Integer.compare(e1.getSalary(),e2.getSalary()));
System.out.println(employeeOptional);
//找出工資最少的
Optional<Employee> employee = employeeList.stream().min((e1,e2)->Integer.compare(e1.getSalary(),e2.getSalary()));
System.out.println(employee);
//返回姓名列表
List<String> names = employeeList.stream().map(c->c.getName()).collect(Collectors.toList());
System.out.println(names);
System.out.println(">>>>>>>>>>>");
//List轉化Map
Map<String,Employee> employeeMap = employeeList.stream().collect(Collectors.toMap((key->key.getName()),(value->value)));
employeeMap.forEach((key,value)-> System.out.println(key + "=" + value));
//統計辦公室是New York的個數
long officeCount = employeeList.stream().filter(c->c.getOffice().equals("New York")).count();
System.out.println(officeCount);
long salaryCount = employeeList.stream().filter(c->c.getSalary()>60000).count();
System.out.println(salaryCount);
//List轉化爲Set
Set<String> officeSet = employeeList.stream().map(c->c.getOffice()).distinct().collect(Collectors.toSet());
System.out.println(officeSet);
Set<Integer> salarySet = employeeList.stream().map(c->c.getSalary()).distinct().collect(Collectors.toSet());
System.out.println(salarySet);
//查找辦公室地點是New York的員工
Optional<Employee> optionals = employeeList.stream().filter(c->c.getOffice().equals("New York")).findAny();
System.out.println(optionals);
System.out.println(">>>>>工資降序排序>>>>>");
//按照工資的降序來列出員工信息
List<Employee> sortSalaryEmployeeList = employeeList.stream().sorted((e1,e2)->Integer.compare(e2.getSalary(),e1.getSalary())).collect(Collectors.toList());
System.out.println(sortSalaryEmployeeList);
System.out.println(">>>>>姓名升序排序>>>>>");
List<Employee> sortNameEmployeeList = employeeList.stream().sorted((e1,e2)->e1.getName().compareTo(e2.getName())).collect(Collectors.toList());
System.out.println(sortNameEmployeeList);
System.out.println(">>>>獲取工資最高的前2條員工信息");
List<Employee> dispaly2EmployeeList = employeeList.stream().sorted((e1,e2)->Integer.compare(e2.getSalary(),e1.getSalary())).limit(2).collect(Collectors.toList());
System.out.println(dispaly2EmployeeList);
System.out.println(">>>>獲取平均工資");
OptionalDouble averageSalary = employeeList.stream().mapToInt(c->c.getSalary()).average();
System.out.println(averageSalary);
System.out.println(">>>>獲取工作地點的平均工資");
OptionalDouble optionalDouble = employeeList.stream().filter(c->c.getOffice().equals("New York")).mapToInt(c->c.getSalary()).average();
System.out.println(optionalDouble);
System.out.println(">>>>>>Java8 Optional用法>>>>>>");
Optional<String> stringOptional = Optional.of("test");
System.out.println(stringOptional.get());
Optional<String> isOptional = Optional.ofNullable("hello");
System.out.println(isOptional.isPresent());
System.out.println(isOptional.get());
System.out.println(isOptional.orElse("0"));
System.out.println(">>>>>>>>>>>>");
//Optional<String> optionalVal = Optional.of(null);
// System.out.println(optionalVal);
Optional<String> optional = Optional.ofNullable("optional");
System.out.println(optional);
System.out.println(optional.isPresent());
System.out.println(optional.get());
System.out.println(optional.orElse("haha"));
System.out.println(">>>>>>>>>>>>");
Optional<Employee> employeeOptional_ = employeeList.stream().filter(c->c.getOffice().equals("New York")).findFirst();
System.out.println(employeeOptional_);
}