非空判断
//优化之前
if (obj != null){
//..
}
//优化之后
if (Optional.ofNullable(obj).isPresent()){
//..
}
//优化之前
if (obj == null){
throw new RuntimeException("");
}
//优化之后
Optional.ofNullable(obj).isPresent().orElseThrow(() ->new RuntimeException(""));
//优化之前
if list == null{
return new ArrayList();
}
return list;
//优化之后
return Optional.ofNullable(list).orElse(new ArrayList<>()).get();
//优化前
if (list == null){
return;
}
for (String s : list){
//..
}
//优化后
Optional.ofNullable(list).orElse(new ArrayList<>()).stream().forEach();
求最大值最小值
Integer max = Stream.of(1,2,3,4,5).max(Integer::compareTo).get();
Integer min = Stream.of(1,2,3,4,5).min(Integer::compareTo).get();
去重操作
//优化前
List list = new ArrayList();
list.add(1);
list.add(2);
list.add(1);
Set set = new HashSet(list);
//优化后
List temp =list.distinct().collect(Collectors.toList());
匿名内部类
//优化前
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Java8");
}
}).start();
//优化后
new Thread(() -> System.out.println(“Java8!”));
规约计算
//基于数据流的方式,将流装载成相应的 SummaryStatistics进行归约计算,可以实现更多的操作;
IntSummaryStatistics stats = list.stream().mapToInt(i -> i). summaryStatistics();
int max = stats.getMax(); //获取最大值
int min = stats.getMin(); //获取最小值
double sum = stats.getSum(); //获取总值
double avg = stats.getAverage(); //获取平均值
long count = stats.getCount(); //获取总数量
//排序
//升序
List temp1 = Stream.of(2,1,3,5,0,6).sorted().collect(Collectors.toList());
//自己制定排序方式
List temp2 = Stream.of(2,1,3,5,0,6).sorted((x,y) -> Integer.compare(x,y)).collect(Collectors.toList());
//求和
//优化前
List list = new ArrayList();
Integer sum = 0;
for (Integer i : list){
sum = sum + i;
}
//优化后
//方式一
sum = list.stream().mapToInt(Integer::intValue).sum();
//还有mapToDouble,mapToLong
//方式二
sum = list.stream().reduce((x,y) -> x+y);
//过滤
//优化之前
List list = new ArrayList();
List newList = new ArrayList();
for (Integer i : list){
if (i % 2 ==0){
newList.add(i);
}
}
//优化之后
newList = list.stream().filter(i -> i % 2 ==0).collect(Collectors.toList());
//分组归类
//优化之前
List list= Arrays.asList(
new Student(1,“one”,“zhao”),
new Student(2,“one”,“qian”),
new Student(3,“two”,“sun”)
);
//1.1根据某个属性分组计数
Map<String,Long> map = new HashMap();
for (Student s : list){
if(map.containsKey(s.getGroupId())){
Long l = map.get(s.getGroupId());
map.put(s.getGroupId(),l+1);
}else{
map.put(s.getGroupId(),1L);
}
}
//优化之后
map=list.stream().collect(Collectors.groupingBy(Student::getGroupId,Collectors.counting()));