Java基础 Day21
一、Stream 流
思想:流水线式思想
1、获取流对象(将数据放到流中)
(1)集合获取 Stream 流对象
使用Collection接口的默认方法
default Stream<E> stream() | |
map.entrySet().stream() |
(2)数组获取流对象
使用 Arrays 数组工具类中的静态方法
static <T> Stream<T> stream(T[ ] array) |
(3)零散数据获取流对象
使用 Stream 类中的静态方法 of()
static <T> Stream<T> of(T... values) |
2、中间方法
Stream<T> filter(Predicate<? super T> predicate) | |
Stream<T> limit(long maxSize) | |
Stream<T> skip(long n) | |
Stream<T> distinct() | |
static <T> Stream<T> concat(Stream a, Stream b) |
中间方法调用完成后返回新的 Stream 流可以继续使用,支持链式编程
如果流对象已经被消费过,就不允许再次使用了
3、终结方法
void forEach(Consumer action) | |
long count() |
4、Stream 流的收集操作
把 Stream 流操作后的结果数据转回到集合
R collect(Collector collector) |
Collectors 工具类提供了具体的收集方式
public static <T> Collector toList() | |
public static <T> Collector toSet() | |
public static Collector toMap(Function keyMapper , Function valueMapper) |
ArrayList<String> list = new ArrayList<String>();
list.add("Alice");
list.add("Bob");
list.add("Bobby");
list.add("Charlie");
list.stream().filter(s -> s.startsWith("Bob")).forEach(s->System.out.println(s));// 收集到 List集合
List<Integer> s1 = Stream.of(1, 2, 3).filter(s -> s % 2 == 1).collect(Collectors.toList());// 收集到 Map集合
Map<String,Integer> map = L2.stream().filter(new Predicate<String>() {@Overridepublic boolean test(String s) {return Integer.parseInt(s.split(",")[1]) >= 22;}
}).collect(Collectors.toMap(new Function<String, String>() {@Overridepublic String apply(String s) {return s.split(",")[0];}
}, new Function<String, Integer>() {@Overridepublic Integer apply(String s) {return Integer.parseInt(s.split(",")[1]);}
}));System.out.println(map);
二、File 类
File 类代表操作系统的文件对象(文件、文件夹)
1、构造方法
public File(String pathname) | |
public File(String parent, String child) | |
public File(File parent, String child) |
File 对象可以定位文件和文件夹
File 封装的对象仅仅是一个路径名,这个路径可以是存在的,也可以是不存在的
绝对路径: 从盘符根目录开始,一直到某个具体的文件或文件夹
相对路径: 相对于当前项目
2、判断和查询方法
public boolean isDirectory() | |
public boolean isFile() | |
public boolean exists() | |
public long length() | |
public String getAbsolutePath() | |
public String getPath() | |
public String getName() | |
public long lastModified() |
3、创建和删除方法
public boolean createNewFile() | |
public boolean mkdir() | |
public boolean mkdirs() | |
public boolean delete() |
delete方法不能删除非空文件夹
delete方法不走回收站
4、遍历方法
public File[] listFiles() |
当调用者File表示的路径不存在时,返回null
当调用者File表示的路径是文件时,返回null
当调用者File表示的路径是一个空文件夹时,返回一个长度为0的数组
当调用者File表示的路径是需要权限才能访问的文件夹时,返回null