将流中的数据转成集合类型:
一、将数据收集进一个列表(Stream 转换为 List,允许重复值,有顺序)
//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);
输出结果为:
二、将数据收集进一个集合(Stream 转换为 Set,不允许重复值,没有顺序)
//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);
输出结果为:
三、用自定义的实现Collection的数据结构收集
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);
输出结果为:
四、对Stream的字符串拼接
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")));
输出结果为:
五、其他还有partitioningBy(),分类成一个key为True和Flase的Map。例如
List<String> list = Arrays.asList("java", "python", "C++","php","java");
Map<Boolean, List<String>> result = list.stream().collect(partitioningBy(s -> s.length() > 2));
六、collectingAndThen(),收集之后继续做一些处理。例如
List<String> list = Arrays.asList("java", "python", "C++","php","java");
//收集后转换为不可变List
ImmutableList<String> collect = list.stream().collect(Collectors.collectingAndThen(Collectors.toList(), ImmutableList::copyOf));
总结:
转载自原文链接, 如需删除请联系管理员。
原文链接:Java8新特性Stream之Collectors(toList()、toSet()、toCollection()、joining()、partitioningBy()、collectingAndT),转载请注明来源!