学会了lambda 函数式接口 开启Stream流的操作 ,流的操作并不会对原有的对象产生任何的影响
流分为2种:普通流,并行流(并发专用)
创建方式: .Stream() & parallelStream()
构造流的常用方式
// 1. Individual values
Stream stream = Stream.of("a", "b", "c");
// 2. 数组
String [] strArray = new String[] {"a", "b", "c"};
stream = Stream.of(strArray);
stream = Arrays.stream(strArray);
// 3. 集合
List list = Arrays.asList(strArray);
stream = list.stream();
创建一个1-6乱序的List
List lists = new ArrayList<>();
lists.add(5);lists.add(1);
lists.add(3);lists.add(6);
lists.add(2);lists.add(4);
List里面的数据:
lists.forEach((o)-> System.out.print(o+" "));// 4 3 6 1 5 2
min/max 最小值/最大值
lists.stream().min(Integer::compareTo).get();//1
lists.stream().max(Comparator.naturalOrder()).get();//6
limit/skip limit 返回 Stream 的前面 n 个元素;skip 则是扔掉前 n 个元素
lists.stream().limit(3).forEach((o)-> System.out.print(o+ " "));//5 1 3
lists.stream().skip(3).forEach((o)-> System.out.print(o+ " "));//6 2 4
reduce 加减乘数
lists.stream().reduce((o1,o2)->o1+o2).get();//21
sorted 排序
Stream sorted = lists.stream().sorted(); //默认为升序
sorted.forEach(o -> System.out.print(o + " "));// 1 2 3 4 5 6
Stream sortedDesc = lists.stream().sorted((o1,o2)->o2.compareTo(o1)); //降序
//可将 (o1,o2)->o2.compareTo(o1) 替换为 Comparator.reverseOrder()
sortedDesc.forEach(o -> System.out.print(o + " "));// 6 5 4 3 2 1
//按照平台的orderd(值越小越优先)排序,按照用户的添加顺序(先->后)排序
customerList = customerList.stream().sorted(Comparator.comparing(CustomerPlatformAccountDTO::getOrderd).thenComparing(CustomerPlatformAccountDTO :: getCreatetime, Comparator.reverseOrder()))
.collect(Collectors.toList());
filter 过滤 -- 留下符合条件的
// 过滤掉奇数
lists.stream().filter(o->o%2 == 0).forEach(o-> System.out.print(o + " "));//6 2 4
map 映射处理
// 每个元素+1
lists.stream().map((o)->o = o+1).forEach((o)-> System.out.print(o +" "));//6 2 4 7 3 5
// 将元素值为3 的元素+999
lists.stream().map(o->{ if (o == 3) {o = o+999;}return o; }).forEach((o)-> System.out.print(o+ " "));//5 1 1000 6 2 4
Stream> inputStream = Stream.of(
Arrays.asList(1),
Arrays.asList(2, 3),
Arrays.asList(4, 5, 6)
);
Stream outputStream = inputStream.
flatMap((childList) -> childList.stream());
输出结果:1,2,3,4,5,6
List list = new ArrayList<>();
list.add("大娃");
list.add("二娃");
list.add("三娃");
list.add("四娃");
String one = list.stream().collect(Collectors.joining("-"));
System.out.println(one);//大娃-二娃-三娃-四娃
String two = list.stream().collect(Collectors.joining("-","[","]"));
System.out.println(two);//[大娃-二娃-三娃-四娃]
String three = list.stream().collect(Collectors.joining("->","",""));
System.out.println(three);//大娃->二娃->三娃->四娃
//原始数据 Dog类 成员属性 name,age 对应的 construct,get/set,equals/hashcode/toString方法
List list = new ArrayList<>();
list.add(new Dog("大狗", 10));
list.add(new Dog("旺财", 5));
list.add(new Dog("小狗", 1));
list.add(new Dog("金毛", 3));
list.add(new Dog("泰迪", 1));
list.add(new Dog("哈士奇", 5));
//分组map
Map> map = list.stream().collect(Collectors.groupingBy(Dog::getAge));
map.forEach((key,value)-> System.out.println(key+":"+value));
输出结果:
1:[Dog{name='小狗', age=1}, Dog{name='泰迪', age=1}]
3:[Dog{name='金毛', age=3}]
5:[Dog{name='旺财', age=5}, Dog{name='哈士奇', age=5}]
10:[Dog{name='大狗', age=10}]
public static void main(String[] args) {
//原始数据 Dog类 成员属性 name,age 对应的 construct,get/set,equals/hashcode/toString方法
List list = new ArrayList<>();
list.add(new Dog("大狗",10));
list.add(new Dog("旺财",5));
list.add(new Dog("小狗",1));
list.add(new Dog("金毛",3));
//list转 map
Map map= list.stream().collect(Collectors.toMap(Dog::getName,Dog::getAge,(k1, k2)->k1));
// 遍历 map
System.out.print("输出map:");
map.forEach((key,value)-> System.out.print(key+":"+value));
// 按照key 排序
System.out.print("\n按照key 排序:");
sortByKey(map).forEach((key,value)-> System.out.print(key+":"+value));
// 按照value 倒序排序
System.out.print("\n按照value 降序排序:");
sortByValue(map).forEach((key,value)-> System.out.print(key+":"+value));
// 按照value 排序也可以不借助工具类
map.entrySet().stream().sorted(Map.Entry.comparingByValue((o1,o2)->o1.compareTo(o2))).forEach((o)-> System.out.println(o));
}
/** 工具方法 key升序 */
public static , V > Map sortByKey(Map map) {
// LinkedHashMap 是HashMap的子类 是有序的,如果用HashMap来接收的话 照样是无序排列
Map result = new LinkedHashMap<>();
map.entrySet().stream().sorted(Map.Entry.comparingByKey())
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
return result;
}
/** 工具方法 value倒序 */
public static > Map sortByValue(Map map) {
Map result = new LinkedHashMap<>();
// reversed 降序
map.entrySet().stream() .sorted(Map.Entry.comparingByValue()
.reversed()).forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
return result;
}
输出结果:
输出map:小狗:1旺财:5金毛:3大狗:10
按照key 排序:大狗:10小狗:1旺财:5金毛:3
按照value 降序排序:大狗:10旺财:5金毛:3小狗:1
List
//原始数据 Dog类 成员属性 name,age 对应的 construct,get/set,equals/hashcode/toString方法
List list = new ArrayList<>();
list.add(new Dog("大狗", 10));
list.add(new Dog("旺财", 5));
//list 转 map
Map map = list.stream().collect(Collectors.toMap(Dog::getName, k1 -> k1, (k1, k2) -> k1));
// 遍历 map
System.out.print("输出map:");
map.forEach((key, value) -> System.out.print(key + ":" + value));
System.out.println("\n----------------");
// map 转 list
List resultList = new ArrayList<>();
map.entrySet().stream().forEachOrdered((o)->resultList.add(o.getValue()));
resultList.forEach(System.out::print);
输出结果:
输出map:旺财:Dog{name='旺财', age=5}大狗:Dog{name='大狗', age=10}
----------------
Dog{name='旺财', age=5}Dog{name='大狗', age=10}
Subject subject1 = new Subject("语文", 91.0);
Subject subject2 = new Subject("语文", 94.0);
Subject subject3 = new Subject("语文", 92.0);
Subject subject4 = new Subject("语文", 90.0);
List subjectList = new ArrayList<>();
subjectList.add(subject1);
subjectList.add(subject2);
subjectList.add(subject3);
subjectList.add(subject4);
List subjectListNew = new ArrayList<>();
//排序生效,使用stream和collect
subjectListNew = subjectList.stream().sorted((s1, s2) -> s1.getGrade().compareTo(s2.getGrade())).collect(Collectors.toList());
System.out.println(JSON.toJSONString(subjectListNew));
//[{"grade":90.0,"name":"语文"},{"grade":91.0,"name":"语文"},{"grade":92.0,"name":"语文"},{"grade":94.0,"name":"语文"}]
System.out.println(JSON.toJSONString(subjectList));//原集合没变
//[{"grade":91,"id":1,"name":"语文"},{"grade":94,"id":2,"name":"数学"},{"grade":92,"id":3,"name":"英语"},{"grade":90,"id":4,"name":"语文"}]
//排序生效,不使用stream和collect
subjectList.sort((s1, s2) -> s1.getGrade().compareTo(s2.getGrade()));
System.out.println(JSON.toJSONString(subjectList));//原集合变化
//[{"grade":90.0,"name":"语文"},{"grade":91.0,"name":"语文"},{"grade":92.0,"name":"语文"},{"grade":94.0,"name":"语文"}]
//排序不生效,使用stream时需要在末尾collect
subjectList.stream().sorted((s1, s2) -> s1.getGrade().compareTo(s2.getGrade()));
System.out.println(JSON.toJSONString(subjectList));
//[{"grade":91.0,"name":"语文"},{"grade":94.0,"name":"语文"},{"grade":92.0,"name":"语文"},{"grade":90.0,"name":"语文"}]
//分数升序排列
subjectListNew = subjectList.stream().sorted((s1, s2) -> {
return s1.getGrade().compareTo(s2.getGrade());
}).collect(Collectors.toList());//如果使用分号,需要加{}和return
System.out.println(JSON.toJSONString(subjectListNew));
//[{"grade":90.0,"name":"语文"},{"grade":91.0,"name":"语文"},{"grade":92.0,"name":"语文"},{"grade":94.0,"name":"语文"}]
//分数降序排列
subjectListNew = subjectList.stream().sorted(Comparator.comparingDouble(Subject::getGrade).reversed()).collect(Collectors.toList());
System.out.println(JSON.toJSONString(subjectListNew));
//[{"grade":94.0,"name":"语文"},{"grade":92.0,"name":"语文"},{"grade":91.0,"name":"语文"},{"grade":90.0,"name":"语文"}]
//分数升序排列
subjectListNew = subjectList.stream().sorted(Comparator.comparingDouble(Subject::getGrade)).collect(Collectors.toList());
System.out.println(JSON.toJSONString(subjectListNew));
//[{"grade":90.0,"name":"语文"},{"grade":91.0,"name":"语文"},{"grade":92.0,"name":"语文"},{"grade":94.0,"name":"语文"}]
List 检测重复的元素 并返回
public static List
getDuplicateElements(List list, boolean flag) {
return list.stream()
.map(e -> { // 获取deptCode或deptAlias的Stream
return flag ? e.getDeptCode() : e.getDeptName();
}).collect(Collectors.toMap(e -> e, e -> 1, (a, b) -> a + b)) // 获得元素出现频率的 Map,键为元素,值为元素出现的次数
.entrySet().stream() // 所有 entry 对应的 Stream
.filter(entry -> entry.getValue() > 1) // 过滤出元素出现次数大于 1 的 entry
.map(entry -> entry.getKey()) // 获得 entry 的键(重复元素)对应的 Stream
.collect(Collectors.toList()); // 转化为 List
}
List去重
List newList = list.stream().distinct().collect(Collectors.toList());
System.out.println(“java8新特性stream去重:”+newList);