stream2
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector; public class MyListCollector<T> implements Collector<T, List<T>, List<T>>{ @Override
public Supplier<List<T>> supplier() {
return ArrayList<T>::new;
} @Override
public BiConsumer<List<T>, T> accumulator() {
// return ArrayList<T>::add;
return List::add;
} @Override
public BinaryOperator<List<T>> combiner() {
return null;
} @Override
public Function<List<T>, List<T>> finisher() {
return null;
} @Override
public Set<Characteristics> characteristics() {
return null;
}
}
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector; import static java.util.stream.Collector.Characteristics.CONCURRENT;
import static java.util.stream.Collector.Characteristics.IDENTITY_FINISH;
import static java.util.stream.Collector.Characteristics.UNORDERED; public class MySetCollector<T> implements Collector<T, Set<T>, Set<T>> { @Override
public Supplier<Set<T>> supplier() {
System.out.println("supplier");
return HashSet<T>::new;
} // 如果return HashSet<T>::add,那么会编译报错,原因在于
// 如果这里return的是HashSet,而supplier方法返回的是TreeSet
// 那么显然,中间用于累积的容器的类型二者是不一致的;就会出现问题
// 如果这里使用了Set::add,即接口类型,那么它就会兼容于supplier
// 所返回的容器类型
// 总之:这里return的类型必须要与泛型的类型保持完全一致
@Override
public BiConsumer<Set<T>, T> accumulator() {
System.out.println("accumulator");
// return Set<T>::add; return (set, item) -> {
System.out.println(item + ", " + set + ", " + Thread.currentThread().getName() );
set.add(item);
};
} @Override
public BinaryOperator<Set<T>> combiner() {
System.out.println("combiner"); return (set1, set2) -> {
set1.addAll(set2);
return set1;
};
} @Override
public Function<Set<T>, Set<T>> finisher() {
System.out.println("finisher"); return Function.identity(); // 对于IDENTITY_FINISH来说,该方法可以直接抛出异常,该方法实际上并不会被调用
// throw new UnsupportedOperationException();
} // 该方法会被调用2次,分别用于确定UNORDERED与IDENTITY_FINISH
@Override
public Set<Characteristics> characteristics() {
System.out.println("characteristics"); return Collections.unmodifiableSet(EnumSet.of(IDENTITY_FINISH, CONCURRENT, UNORDERED));
} public static void main(String[] args) {
List<String> list = Arrays.asList("hello", "world", "welcome", "hello", "a", "b", "c", "d", "e", "f", "g", "aa", "bb", "cc", "dd", "ee", "ff", "gg", "hh", "ii");
Set<String> preSet = new HashSet<>();
preSet.addAll(list); System.out.println(preSet); Set<String> set = preSet.stream().parallel().collect(new MySetCollector<>()); System.out.println("---------------"); System.out.println(set); // System.out.println(Runtime.getRuntime().availableProcessors());
}
}
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector; public class MySetCollector2<T> implements Collector<T, Set<T>, Map<T, T>> { @Override
public Supplier<Set<T>> supplier() {
System.out.println("supplier invoked!"); // 串行流调用时,只会生成一个HashSet
// 并行流调用时,每个线程都会生成一个HashSet
/**
* * A a1 = supplier.get();
* accumulator.accept(a1, t1);
* accumulator.accept(a1, t2);
* R r1 = finisher.apply(a1); // result without splitting
*
* A a2 = supplier.get();
* accumulator.accept(a2, t1);
* A a3 = supplier.get();
* accumulator.accept(a3, t2);
* R r2 = finisher.apply(combiner.apply(a2, a3)); // result with splitting
*/ return () -> {
System.out.println("~~~~~~~~~~~~~~~~~");
return new HashSet<T>();
}; // return HashSet<T>::new;
} @Override
public BiConsumer<Set<T>, T> accumulator() {
System.out.println("accumulator invoked!"); return (set, item) -> {
System.out.println("accumulator, " + set + ", " + Thread.currentThread().getName());
set.add(item);
};
} @Override
public BinaryOperator<Set<T>> combiner() {
System.out.println("combiner invoked!"); return (set1, set2) -> {
System.out.println("combiner, " + set1 + ", " + set2);
set1.addAll(set2);
return set1;
};
} @Override
public Function<Set<T>, Map<T, T>> finisher() {
System.out.println("finisher invoked!"); return set -> {
System.out.println("finisher, " + set);
Map<T, T> map = new TreeMap<>();
set.stream().forEach(item -> map.put(item, item));
return map;
};
} @Override
public Set<Characteristics> characteristics() {
System.out.println("characteristics invoked!");
// return Collections.unmodifiableSet(EnumSet.of(Characteristics.UNORDERED, Characteristics.IDENTITY_FINISH));
return Collections.unmodifiableSet(EnumSet.of(Characteristics.UNORDERED, Characteristics.CONCURRENT));
} public static void main(String[] args) {
System.out.println(Runtime.getRuntime().availableProcessors()); List<String> list = Arrays.asList("hello", "world", "welcome", "hello", "a", "b", "c", "d", "e", "f", "g");
Set<String> set = new HashSet<>();
set.addAll(list); System.out.println("set: " + set); System.out.println("----------"); //串行执行时combiner并不会得到调用,combiner只在并行流时会得到调用
// Map<String, String> map = set.stream().parallel().sequential().parallel().collect(new MySetCollector2<>());
Map<String, String> map = set.parallelStream().collect(new MySetCollector2<>());
System.out.println(map);
}
}
import java.util.Arrays;
import java.util.Comparator;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.Optional; import static java.util.stream.Collectors.averagingInt;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.maxBy;
import static java.util.stream.Collectors.minBy;
import static java.util.stream.Collectors.partitioningBy;
import static java.util.stream.Collectors.summarizingInt;
import static java.util.stream.Collectors.summingInt;
import static java.util.stream.Collectors.toList; public class StreamTest1 { public static void main(String[] args) {
Student student1 = new Student("zhangsan", 80);
Student student2 = new Student("lisi", 90);
Student student3 = new Student("wangwu", 100);
Student student4 = new Student("zhaoliu", 90);
Student student5 = new Student("zhaoliu", 90); List<Student> students = Arrays.asList(student1, student2, student3, student4, student5); // List<Student> students1 = students.stream().collect(toList());
// students1.forEach(System.out::println);
// System.out.println("------------");
//
//
// System.out.println("count: " + students.stream().collect(counting()));
// System.out.println("count: " + students.stream().count());
// System.out.println("------------");
//
//
// students.stream().collect(minBy(Comparator.comparingInt(Student::getScore))).ifPresent(System.out::println);
//
// students.stream().collect(maxBy(Comparator.comparingInt(Student::getScore))).ifPresent(System.out::println);
//
// System.out.println(students.stream().collect(averagingInt(Student::getScore)));
//
// System.out.println(students.stream().collect(summingInt(Student::getScore)));
//
// IntSummaryStatistics intSummaryStatistics = students.stream().collect(summarizingInt(Student::getScore));
// System.out.println(intSummaryStatistics);
// System.out.println("------------");
//
// System.out.println(students.stream().map(Student::getName).collect(joining()));
// System.out.println(students.stream().map(Student::getName).collect(joining(", ")));
// System.out.println(students.stream().map(Student::getName).collect(joining(", ", "<begin> ", " <end>")));
// System.out.println("------------");
// // Map<Integer, Map<String, List<Student>>> map = students.stream().
// collect(groupingBy(Student::getScore, groupingBy(Student::getName)));
// System.out.println(map);
// System.out.println("------------"); //
// Map<Boolean, List<Student>> map2 = students.stream().
// collect(partitioningBy(student -> student.getScore() > 80));
// System.out.println(map2);
// System.out.println("------------");
// // Map<Boolean, Map<Boolean, List<Student>>> map3 = students.stream().
// collect(partitioningBy(student -> student.getScore() > 80,
// partitioningBy(student -> student.getScore() > 90)));
// System.out.println(map3);
// System.out.println("------------"); //
// Map<Boolean, Long> map4 = students.stream().
// collect(partitioningBy(student -> student.getScore() > 80, counting()));
// System.out.println(map4);
// System.out.println("------------");
////
// Map<String, Student> map5 = students.stream().
// collect(groupingBy(Student::getName,
// collectingAndThen(minBy(Comparator.comparingInt(Student::getScore)),
// Optional::get)));
// System.out.println(map5);
}
}
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List; public class StreamTest2 { public static void main(String[] args) { List<String> list = Arrays.asList("nihao", "hello", "world", "welcome"); // Collections.sort(list, (item1, item2) -> item1.length() - item2.length());
// Collections.sort(list, (item1, item2) -> item2.length() - item1.length()); // Collections.sort(list, Comparator.comparingInt(String::length).reversed());
//// 此处lambda参数的类型推断无法推断出item为String类型,需要显式指定;原因在于这是一个独立的参数,并不是通过list调用方法来得出的
// Collections.sort(list, Comparator.comparingInt((String item) -> item.length()).reversed());
//// 如下代码无法编译通过,因为lambda参数要求参数类型应该是String或是String的父类,而Boolean则不是
// Collections.sort(list, Comparator.comparingInt((Boolean item) -> 1).reversed()); //// Collections的sort就是调用List的sort实现的
// list.sort(Comparator.comparingInt(String::length).reversed());
//// 如下代码必须要显式声明item的类型为String
// list.sort(Comparator.comparingInt((String item) -> item.length()).reversed());
//
//
// Collections.sort(list, Comparator.comparingInt(String::length).thenComparing(String.CASE_INSENSITIVE_ORDER));
//
// // 为何下面这个thenComparing中的参数类型可以推断出来?
// Collections.sort(list, Comparator.comparingInt(String::length).
// thenComparing((item1, item2) -> item1.toLowerCase().compareTo(item2.toLowerCase())));
// Collections.sort(list, Comparator.comparingInt(String::length).
// thenComparing(Comparator.comparing(String::toLowerCase)));
// Collections.sort(list, Comparator.comparingInt(String::length).
// thenComparing(Comparator.comparing(String::toLowerCase, Comparator.reverseOrder())));
////
// // welcome, world, nihao, hello
// Collections.sort(list, Comparator.comparingInt(String::length).reversed().
// thenComparing(Comparator.comparing(String::toLowerCase, Comparator.reverseOrder())));
//
// // welcome, world, nihao, hello, 注意:thenComparing都是根据前一个compare的结果来决定此次是否进行再次排序,
// // 如果前一次排序不返回0,那么此次排序结果就直接返回之前的排序结果 Collections.sort(list, Comparator.comparingInt(String::length).reversed().
thenComparing(Comparator.comparing(String::toLowerCase, Comparator.reverseOrder())).
thenComparing(Comparator.reverseOrder())); System.out.println(list);
}
}
public class Student {
private String name;
private int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", score=" + score +
'}';
}
}
stream2的更多相关文章
- java8 Stream2
new Thread(() -> System.out.println("lambda表达式,取代匿名函数......")).start(); Stream.of(" ...
- 深入node之Transform
Transform流特性 在开发中直接接触Transform流的情况不是很多,往往是使用相对成熟的模块或者封装的API来完成流的处理,最为特殊的莫过于through2模块和gulp流操作.那么,Tra ...
- 最好的.NET开源免费ZIP库DotNetZip(.NET组件介绍之三)
在项目开发中,除了对数据的展示更多的就是对文件的相关操作,例如文件的创建和删除,以及文件的压缩和解压.文件压缩的好处有很多,主要就是在文件传输的方面,文件压缩的好处就不需要赘述,因为无论是开发者,还是 ...
- 一款开源免费的.NET文档操作组件DocX(.NET组件介绍之一)
在目前的软件项目中,都会较多的使用到对文档的操作,用于记录和统计相关业务信息.由于系统自身提供了对文档的相关操作,所以在一定程度上极大的简化了软件使用者的工作量. 在.NET项目中如果用户提出了相关文 ...
- 如何运行Spark程序
[hxsyl@CentOSMaster spark-2.0.2-bin-hadoop2.6]# ./bin/spark-submit --class org.apache.spark.examples ...
- 小菜学习设计模式(四)—原型(Prototype)模式
前言 设计模式目录: 小菜学习设计模式(一)—模板方法(Template)模式 小菜学习设计模式(二)—单例(Singleton)模式 小菜学习设计模式(三)—工厂方法(Factory Method) ...
- C# DESC加密
DESC加密方法 直接上代码: 1.加密 /// <summary> /// 加密 /// </summary> /// <param name="obj&qu ...
- [MVC_Json序列化]Json字符串反序列化成C#对象
上一篇中有Json序列化相关问题得到了解决. 那么结果集为Json串时,如何将Json串转成C#对象呢? 现举例说明: -现有如下字符串数据 string k = "{\"ring ...
- Matlab绘图函数一览
要查看Matlab所有绘图函数,请从Matlab主界面菜单查看“绘图目录”,或从Matlab帮助文档查看“Types of MATLAB Plots”(在线版本).本文的图和英文解释摘自Matlab帮 ...
随机推荐
- 树莓派研究笔记(6)-- Lakka模拟游戏机
我发现lakka的支持的游戏平台特别多,包括国产的OrangePI,真是太棒了.我们可以用这个来打造一个全功能模拟器平台.(删除线部分为Orange PI 测试成功内容,但在树莓派上无需那些操作) 访 ...
- C++笔记--指针数组和结构
指针 类型为T*的变量能保存一个类型T对象的地址 Char c=‘a’:Char * p=& c://保存了c的地址 指针的操作一般都是间接的引用,就是相当于引用指针所指的对象. 0是一个特殊 ...
- 《Head First Servlets & JSP》-6-会话管理-listener etc. demo
工程结构 上下文参数示例 示例程序展示了如何从上下文读取参数,并在上下文监听器中生成属性对象和在上下文中设置属性. 建立一个简单的JavaBean对象作为属性:Dog.java package com ...
- 数据库(学习整理)----6--Oracle如何快速备份和多次备份数表数据
1.说明: 这里假设一种应用场景! 假设,银行系统中有大量的数据需要及时备份,如何才能快速高效呢! 条件需求: (1).不能设置同步锁(设置的会影响银行正常业务进行!使得银行系统处于维护状态,这是不 ...
- Java50道经典习题-程序26 求星期
题目:请输入星期几的第一个字母来判断一下是星期几,如果第一个字母一样,则继续 判断第二个字母.分析:用情况语句比较好,如果第一个字母一样,则判断用情况语句或if语句判断第二个字母.周一至周日的英文单词 ...
- 接口型模式(二)Bridge(桥接)模式
目的: 将抽象与抽象方法的实现相分离,使得它们可以独自变化.常用于驱动程序中,使得顶层逻辑不受驱动底层改变的影响,如数据库的变化. 关键词:Bridge, 抽象与实现分离,驱动程序 必要性:从一般抽象 ...
- WPF之MVVM模式(3)
有种想写一个MVVM框架的冲动!!! 1.Model中的属性应不应该支持OnPropertyChanged事件? 不应该.应该有ViewModel对该属性进行封装,由ViewModel提供OnProp ...
- easyui textbox 设置只读不可编辑状态
在使用easyul的时候,发现输入框内容及不容易获取与设置,用jQuery的方式大部分失效.依稀记得好像是因为easyul会在原页面的基础上,生成了一些新的独有样式,并且暂时覆盖掉使用了easyul的 ...
- android studio中使用x5 webview来读写cookies的问题
本人新手,刚接触AS也没有多久,记录下两个问题. 1. 怎么在android studio中写入cookies 把写入cookies的动作放在了主界面的onCreate事件中了,看了腾讯的说明,说是要 ...
- Unobrusive Ajax使用
mark一下:[ASP.NET MVC 小牛之路]14 - Unobtrusive Ajax篇文章,果断记下来,网址: http://www.cnblogs.com/willick/p/3418517 ...