1、stream排序
Java8排序stream.sorted()
package com.stream.demo;
public class Student implements Comparable<Student> {
private int id;
private String name;
private int age;
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public int compareTo(Student ob) {
return name.compareTo(ob.getName());
}
}
使用
package com.stream.demo;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class StreamListDemo {
public static void main(String[] args) {
List<Student> list = new ArrayList<>();
list.add(new Student(1, "Mahesh", 12));
list.add(new Student(2, "Suresh", 15));
list.add(new Student(3, "Nilesh", 10));
//==================================================================
List<Student> slist = list.stream().sorted().collect(Collectors.toList());
slist.forEach(e -> System.out.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
//==================================================================
slist = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
slist.forEach(e -> System.out.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
//========================================================================================
// 或者这种写法 .sorted((u1,u2)->{return u2.getxxx().compareTo(u1.getxxx()); })
slist = list.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
slist.forEach(e -> System.out.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
//==================================================================
slist = list.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());
slist.forEach(e -> System.out.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
//==================================================================
//多字段排序
// 先以属性一升序,升序结果进行属性一降序,再进行属性二升序,结果进行属性一降序属性二降序
list.stream().sorted(Comparator.comparing(类::属性一).reversed().thenComparing(类::属性二).reversed());
}
}
2、stream去重
一、使用distinct()多字段去重
distinct() 根据hashCode() 作为去重的 可以重写hashCode方法
//重写实体Person
@Override
public int hashCode() {
return Objects.hash(getName(), getAge());
}
Person person1 = new Person();
person1.setAge(18);
person1.setName("18");
Person person2 = new Person();
person2.setAge(19);
person2.setName("19");
Person person3 = new Person();
person3.setAge(19);
person3.setName("19");
List<Person> people = new ArrayList<>();
people.add(person1);
people.add(person2);
people.add(person3);
List<Person> collect1 = people.stream().distinct().collect(Collectors.toList());
二、使用stream多字段无需重写hashcode方法
// 根据id去重
list = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() ->
new TreeSet<>(Comparator.comparing(Person::getPackId))),ArrayList::new));
// 根据id和ctn去重
list = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() ->
new TreeSet<>(Comparator.comparing(t -> t.getPackId() + "#" + t.getActCtn()))),ArrayList::new));
当使用多个字段进行去重时,中间用 “#” 连接即可
3、转map
public class DemoListToMap {
List<Student> list = Arrays.asList(new Student(1, 18, "阿龙", GenderColumn.BOY.getCode()),
new Student(2, 17, "小花", GenderColumn.GIRL.getCode()),
new Student(3, 17, "阿浪", GenderColumn.LADYBOY.getCode()));
@Test
public void listToMapByObjectValue(){
// value 为对象 Function.identity()代替student -> student
Map<Integer, Student> map = list.stream().collect(Collectors.toMap(Student::getId, student -> student));
// 遍历打印结果
map.forEach((key, value) -> {
System.out.println("key: " + key + " value: " + value);
});
}
}
出现相同的话会报错 解决方法
@Test
public void listToMapByAgeKey(){
// value 为对象中的属性
Map<Integer, String> map = list.stream().collect(
//舍相同的key2
Collectors.toMap(Student::getAge, Student::getName, (key1, key2) -> key1)
);
map.forEach((key, value) -> {
System.out.println("key: " + key + " value: " + value);
});
}
4、分组
Map<String, List<Employee>> map = emps.stream().collect(Collectors.groupingBy(Employee::getCity));
map.forEach((key,val)->{
System.out.println("城市:"+key+" ---员工集: "+val);
});
/**
* 城市:广州 ---员工集: [Employee{name='1', city='广州', sales=100}, Employee{name='5', city='广州', sales=20}, Employee{name='6', city='广州', sales=30}, Employee{name='8', city='广州', sales=30}]
* 城市:上海 ---员工集: [Employee{name='0', city='上海', sales=30}]
* 城市:杭州 ---员工集: [Employee{name='2', city='杭州', sales=50}, Employee{name='7', city='杭州', sales=30}]
* 城市:北京 ---员工集: [Employee{name='3', city='北京', sales=30}, Employee{name='4', city='北京', sales=50}, Employee{name='9', city='北京', sales=30}]
*/
计算分组总额
Map<String, Integer> map = emps.stream().
collect(Collectors.groupingBy(Employee::getCity, Collectors.summingInt(Employee::getSales)));
// 先按city分组 再对组里面的成员,统计总销售额
map.forEach((key,val)->{
System.out.println("城市:"+key+" 销售总额:"+val);
});
/**
* 城市:广州 销售总额:120
* 城市:上海 销售总额:50
* 城市:杭州 销售总额:180
* 城市:北京 销售总额:50
*/
查看分组去重分组用户名字
List<Employee> emps = getEmps();
Map<String, Set<String>> map = emps.stream().collect(Collectors.groupingBy(Employee::getCity, Collectors.mapping(Employee::getName, Collectors.toSet())));
map.forEach((key,val)->{
System.out.println(""+key+" ---人员姓名: "+val);
});
计算分组中最大值
Map<String, Employee> map = emps.stream().collect(Collectors.groupingBy(Employee::getCity,
Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparingInt(Employee::getSales)), Optional::get)));
map.forEach((key,val)->{
System.out.println("城市:"+key+" 销售额最大员工:"+val);
});
分组名字排序 并去重分组重复
TreeMap<String, Set<String>> map = emps.stream().collect(Collectors.groupingBy(Employee::getCity, TreeMap::new, Collectors.mapping(Employee::getName, Collectors.toSet())));
map.forEach((key,val)->{
System.out.println("城市:"+key+" 姓氏集:"+val);
});
分组后做额外的指定的形式进行返回 返回类型随意
Integer collect = users.stream().filter(u -> true).collect(Collectors.collectingAndThen(Collectors.groupingBy(User::getId), map -> {
Integer integer1 = null;
for (Integer integer : map.keySet()) {
integer1 = map.get(integer).stream().map(User::getId).reduce(Integer::sum).get();
}
return integer1;
}));
5、anyMatch / allMatch / noneMatch匹配用法
anyMatch:判断的条件里,任意一个元素成功,返回true
allMatch:判断条件里的元素,所有的都是,返回true
noneMatch:与allMatch相反,判断条件里的元素,所有的都不是,返回true
List<Integer> list = Arrays.asList(1, 2, 1, 1, 1);
boolean anyMatch = list.stream().anyMatch(f -> f == (1));
boolean allMatch = list.stream().allMatch(f -> f == (1));
boolean noneMatch = list.stream().noneMatch(f -> f == (1));
6、交集、并集、差集、去重并集
表达式可以使用 代替 、、、、集合::方法
//List<String> reduce2 = list2.stream().filter(item -> !list1.contains(item)).collect(Collectors.toList());
List<String> reduce2 = list2.stream().filter(list1::contains).collect(Collectors.toList());
public static void main(String[] args) {
List<String> list1 = new ArrayList<String>();
list1.add("1");
list1.add("2");
list1.add("3");
list1.add("5");
list1.add("6");
List<String> list2 = new ArrayList<String>();
list2.add("2");
list2.add("3");
list2.add("7");
list2.add("8");
// 交集
List<String> intersection = list1.stream().filter(item -> list2.contains(item)).collect(Collectors.toList());
System.out.println("---交集 intersection---");
intersection.parallelStream().forEach(System.out :: println);
// 差集 (list1 - list2)
List<String> reduce1 = list1.stream().filter(item -> !list2.contains(item)).collect(Collectors.toList());
System.out.println("---差集 reduce1 (list1 - list2)---");
reduce1.parallelStream().forEach(System.out :: println);
// 差集 (list2 - list1)
List<String> reduce2 = list2.stream().filter(item -> !list1.contains(item)).collect(Collectors.toList());
System.out.println("---差集 reduce2 (list2 - list1)---");
reduce2.parallelStream().forEach(System.out :: println);
// 并集
List<String> listAll = list1.parallelStream().collect(Collectors.toList());
List<String> listAll2 = list2.parallelStream().collect(Collectors.toList());
listAll.addAll(listAll2);
System.out.println("---并集 listAll---");
listAll.parallelStream().forEachOrdered(System.out :: println);
// 去重并集
List<String> listAllDistinct = listAll.stream().distinct().collect(Collectors.toList());
System.out.println("---得到去重并集 listAllDistinct---");
listAllDistinct.parallelStream().forEachOrdered(System.out :: println);
System.out.println("---原来的List1---");
list1.parallelStream().forEachOrdered(System.out :: println);
System.out.println("---原来的List2---");
list2.parallelStream().forEachOrdered(System.out :: println);
}
7、map分组后排序
HashMap<Integer, Integer> map = new HashMap<>();
//根据key排序
map.entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toList());
//根据key倒叙
map.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByKey())).collect(Collectors.toList());
// tree
TreeMap<Integer, User> integerObjectTreeMap = new TreeMap<>((o1, o2) -> o1-o1);
integerObjectTreeMap.putAll(map);
//tree 倒叙
TreeMap<Integer, User> integerObjectTreeMap = new TreeMap<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
}.reversed());
8、单个字段的求和
//第一种方式
int suma = list.stream().map(e -> e.getAge()).reduce(Integer::sum).get();//求和
int maxa = list.stream().map(e -> e.getAge()).reduce(Integer::max).get();//最大
int mina = list.stream().map(e -> e.getAge()).reduce(Integer::min).get();//最小
//第二种方式
double doublesum = list.stream().mapToDouble(Student::getAge).sum();//和
int intmax = list.stream().mapToInt(Student::getAge).max().getAsInt();//最大
int intmin = list.stream().mapToInt(Student::getAge).min().getAsInt();//最小
double avg = list.stream().mapToDouble(Student::getAge).average().getAsDouble();//平均
9、集合中对象得数组获取
//getCartInfo获取得是数组
List<YxStoreCartQueryVo> cartQueryVos = confirmOrderVos.stream()
.map(ConfirmOrderVo::getCartInfo)
.flatMap(List::stream)
.collect(Collectors.toList());