慕课网996笔记
1.函数式接口
自定义函数接口
- 只有一个方法只有一个方法
- 函数式注解@FunctionInterface
- 函数式接口的抽象方法签名: 函数描述符
可以定义一个或者多个statis方法
可以定义一个default方法
默认函数接口
2 流处理
1. 操作流程
2. 操作分类
3. 操作详解
3. 生成流的四种方式
1. 数值
Stream<Integer> stream = Stream.of(1, 2, 34, 9, 52, 7);
2. 数组,集合
IntStream arrStream = Arrays.stream(arr);
3. 函数
Stream<Double> generate = Stream.generate(Math::random).limit(100L);
4. 文件
Stream<String> lineStream = Files.lines(Paths.get("D:/test.java"));
4. 常见收集器
收集成为一个list
List<Sku> collect = list.stream()
.filter(sku -> sku.getTotalPrice() > 200)
.collect(Collectors.toList());
按照条件分组
List<Sku> collect = list.stream()
.filter(sku -> sku.getTotalPrice() > 200)
.collect(Collectors.toList());
Map<Boolean, List<Sku>> map = list.stream().collect(Collectors.partitioningBy(sku -> sku.getTotalPrice() > 200));
5.资源关闭
传统关闭方式
try->catch->finally
jdk7新关闭方式
try->with->resource
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileCopyTest {
String originUrl ="";
String targetUrl ="";
@Test
public void copyFile() {
// file in/out put stream
FileInputStream originStream = null;
FileOutputStream fileOutputStream = null;
File file;
try {
originStream = new FileInputStream(originUrl);
fileOutputStream = new FileOutputStream(targetUrl);
int content;
// iterator and read/out put byte
while ((content = originStream.read()) != -1) {
fileOutputStream.write(content);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (originStream != null) {
try {
originStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test
public void copyFileNewTest() {
try (
FileInputStream inputStream = new FileInputStream(originUrl);
FileOutputStream outputStream = new FileOutputStream(targetUrl);
) {
int content;
// iterator and read/out put byte
while ((content = inputStream.read()) != -1) {
outputStream.write(content);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
6 Optional空判断
@Test
public void optionTest() {
//三总定义方式
Optional<Object> o = Optional.empty();
Optional<Integer> integer = Optional.of(1);
Optional<Object> optional = Optional.ofNullable(null);
//空值操作
boolean present = optional.isPresent();
optional.ifPresent(System.out::println);
Object we = optional.orElse("we");
optional.orElseGet(() -> { return "else"; });
optional.orElseThrow(() -> { throw new RuntimeException("引用缺失"); });
}