Java8新特性Stream之Collectors(toList()、toSet()、toCollection()、joining()、partitioningBy()、collectingAndT)
将流中的数据转成集合类型:
//1.将数据收集进一个列表(Stream 转换为 List,允许重复值,有顺序)
//创建流
Stream<String> language = Stream.of("java", "python", "C++","php","java");
List<String> listResult = language.collect(Collectors.toList());
result.forEach(System.out::println);
//2.stream()代替流
List<String> list = Arrays.asList("java", "python", "C++","php","java");
List<String> listResult = list.stream().collect(Collectors.toList());
listResult.forEach(System.out::println);
//1.将数据收集进一个集合(Stream 转换为 Set,不允许重复值,没有顺序)
Stream<String> language = Stream.of("java", "python", "C++","php","java");
Set<String> setResult = language.collect(Collectors.toSet());
setResult.forEach(System.out::println);
List<String> list = Arrays.asList("java", "python", "C++","php","java");
//用LinkedList收集
List<String> linkedListResult = list.stream().collect(Collectors.toCollection(LinkedList::new));
linkedListResult.forEach(System.out::println);
System.out.println("--------------");
//用CopyOnWriteArrayList收集
List<String> copyOnWriteArrayListResult = list.stream().collect(Collectors.toCollection(CopyOnWriteArrayList::new));
copyOnWriteArrayListResult.forEach(System.out::println);
System.out.println("--------------");
//用TreeSet收集
TreeSet<String> treeSetResult = list.stream().collect(Collectors.toCollection(TreeSet::new));
treeSetResult.forEach(System.out::println);
List<String> list = Arrays.asList("java", "python", "C++","php","java");
//直接将输出结果拼接
System.out.println(list.stream().collect(Collectors.joining()));
//每个输出结果之间加拼接符号“|”
System.out.println(list.stream().collect(Collectors.joining(" | ")));
//输出结果开始头为Start--,结尾为--End,中间用拼接符号“||”
System.out.println(list.stream().collect(Collectors.joining(" || ", "Start--", "--End")));
List<String> list = Arrays.asList("java", "python", "C++","php","java");
Map<Boolean, List<String>> result = list.stream().collect(partitioningBy(s -> s.length() > 2));
List<String> list = Arrays.asList("java", "python", "C++","php","java");
//收集后转换为不可变List
ImmutableList<String> collect = list.stream().collect(Collectors.collectingAndThen(Collectors.toList(), ImmutableList::copyOf));