建实体类:
public class Person {
private String name;
private Integer age;
private String sex;
public Person(String name, Integer age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
编写main方法
多管道处理:personList.parallelStream()
单管道处理:personList.stream()
import com.alibaba.fastjson.JSON;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author wwy
* @date 2020/9/8 11:22
*/
public class Test2 {
public static void main(String[] args) {
List<Person> personList = Lists.newArrayList(
new Person("张三",13,"男"),
new Person("张四",14,"女"),
new Person("张五",15,"男"),
new Person("张六",16,"女"),
new Person("张七",17,"男"),
new Person("张八",18,"女"),
new Person("张九",19,"男"),
new Person("张十",20,"女"));
//将list中实体类按照指定属性聚类进行map封装---方法1
Map<String,List<Person>> map = personList.stream().collect(
Collectors.groupingBy(Person::getSex));
System.out.println(JSON.toJSONString(map));
//将list中实体类按照指定属性聚类进行map封装---方法2
Map<Integer, List<Person>> map = Maps.newHashMap();
for (Person person : personList) {
//computeIfAbsent 如果存在查询的key则返回key对应的value,否则返回第二个参数执行结果
List<Person> list = map.computeIfAbsent(person.getAge(), k -> new ArrayList<>());
list.add(person);
}
//将list中实体按照指定属性key-value进行聚类
Map<Integer,String> map1 = personList.stream().collect(Collectors.toMap(Person::getAge,Person::getName));
System.out.println(JSON.toJSONString(map1));
//指定实体数据组装为list
List<Integer> list3 = personList.stream().map(Person::getAge).collect(Collectors.toList());
System.out.println(JSON.toJSONString(list3));
//将list转为string并用逗号拼接
String str4 = StringUtils.join(personList.stream().map(Person::getAge).collect(Collectors.toList()).toArray(), ",");
System.out.println(str4);
//将list转为string并用逗号拼接
StringBuffer sb5 = new StringBuffer();
sb5.append(Joiner.on(",").join(personList.stream().map(Person::getAge).collect(Collectors.toList())));
System.out.println(sb5.toString());
//将groupingBy后得到的map结果中的value从List格式转为单个对象格式
//第一种
Map<Long, BusinessLineGroup> collect = businessLineGroup.stream().collect(Collectors.groupingBy(BusinessLineGroup::getId, Collector.of(BusinessLineGroup::new, (acc, curr) -> acc = curr, (a, b) -> a, Collector.Characteristics.IDENTITY_FINISH)));
//第二种
Map<Long, Optional<BusinessLineGroup>> collect1 = collect = businessLineGroup.stream().collect(Collectors.groupingBy(BusinessLineGroup::getId, Collectors.maxBy((o1, o2) -> 0)));
//第三种
Map<String, Person> collect = personList.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparingInt(Person::getAge)), Optional::get)));
}
}
数据准备:
public Product(Long id, Integer num, BigDecimal price, String name, String category) {
this.id = id;
this.num = num;
this.price = price;
this.name = name;
this.category = category;
}
Product prod1 = new Product(1L, 1, new BigDecimal("15.5"), "面包", "零食");
Product prod2 = new Product(2L, 2, new BigDecimal("20"), "饼干", "零食");
Product prod3 = new Product(3L, 3, new BigDecimal("30"), "月饼", "零食");
Product prod4 = new Product(4L, 3, new BigDecimal("10"), "青岛啤酒", "啤酒");
Product prod5 = new Product(5L, 10, new BigDecimal("15"), "百威啤酒", "啤酒");
List<Product> prodList = Lists.newArrayList(prod1, prod2, prod3, prod4, prod5);
按类目分组
Map> prodMap= prodList.stream().collect(Collectors.groupingBy(Product::getCategory));
//{"啤酒":[{"category":"啤酒","id":4,"name":"青岛啤酒","num":3,"price":10},{"category":"啤酒","id":5,"name":"百威啤酒","num":10,"price":15}],"零食":[{"category":"零食","id":1,"name":"面包","num":1,"price":15.5},{"category":"零食","id":2,"name":"饼干","num":2,"price":20},{"category":"零食","id":3,"name":"月饼","num":3,"price":30}]}
按照几个属性拼接分组:
Map> prodMap = prodList.stream().collect(Collectors.groupingBy(item -> item.getCategory() + "_" + item.getName()));
//{"零食_月饼":[{"category":"零食","id":3,"name":"月饼","num":3,"price":30}],"零食_面包":[{"category":"零食","id":1,"name":"面包","num":1,"price":15.5}],"啤酒_百威啤酒":[{"category":"啤酒","id":5,"name":"百威啤酒","num":10,"price":15}],"啤酒_青岛啤酒":[{"category":"啤酒","id":4,"name":"青岛啤酒","num":3,"price":10}],"零食_饼干":[{"category":"零食","id":2,"name":"饼干","num":2,"price":20}]}
根据不同条件分组
Map> prodMap= prodList.stream().collect(Collectors.groupingBy(item -> {
if(item.getNum() < 3) {
return "3";
}else {
return "other";
}
}));
//{"other":[{"category":"零食","id":3,"name":"月饼","num":3,"price":30},{"category":"啤酒","id":4,"name":"青岛啤酒","num":3,"price":10},{"category":"啤酒","id":5,"name":"百威啤酒","num":10,"price":15}],"3":[{"category":"零食","id":1,"name":"面包","num":1,"price":15.5},{"category":"零食","id":2,"name":"饼干","num":2,"price":20}]}
要实现多级分组,我们可以使用一个由双参数版本的Collectors.groupingBy工厂方法创 建的收集器,它除了普通的分类函数之外,还可以接受collector类型的第二个参数。那么要进 行二级分组的话,我们可以把一个内层groupingBy传递给外层groupingBy,并定义一个为流 中项目分类的二级标准。
Map>> prodMap= prodList.stream().collect(Collectors.groupingBy(Product::getCategory, Collectors.groupingBy(item -> {
if(item.getNum() < 3) {
return "3";
}else {
return "other";
}
})));
//{"啤酒":{"other":[{"category":"啤酒","id":4,"name":"青岛啤酒","num":3,"price":10},{"category":"啤酒","id":5,"name":"百威啤酒","num":10,"price":15}]},"零食":{"other":[{"category":"零食","id":3,"name":"月饼","num":3,"price":30}],"3":[{"category":"零食","id":1,"name":"面包","num":1,"price":15.5},{"category":"零食","id":2,"name":"饼干","num":2,"price":20}]}}
求总数
Map prodMap = prodList.stream().collect(Collectors.groupingBy(Product::getCategory, Collectors.counting()));
//{"啤酒":2,"零食":3}
求和
Map prodMap = prodList.stream().collect(Collectors.groupingBy(Product::getCategory, Collectors.summingInt(Product::getNum)));
//{"啤酒":13,"零食":6}
把收集器的结果转换为另一种类型
Map prodMap = prodList.stream().collect(Collectors.groupingBy(Product::getCategory, Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparingInt(Product::getNum)), Optional::get)));
//{"啤酒":{"category":"啤酒","id":5,"name":"百威啤酒","num":10,"price":15},"零食":{"category":"零食","id":3,"name":"月饼","num":3,"price":30}}
联合其他收集器
Map> prodMap = prodList.stream().collect(Collectors.groupingBy(Product::getCategory, Collectors.mapping(Product::getName, Collectors.toSet())));
//{"啤酒":["青岛啤酒","百威啤酒"],"零食":["面包","饼干","月饼"]}
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u014231523/article/details/102535902
————————————————
版权声明:本文为CSDN博主「兴国First」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u014231523/article/details/102535902
下面代码以自然序排序一个list
list.stream().sorted()
自然序逆序元素,使用Comparator 提供的reverseOrder() 方法
list.stream().sorted(Comparator.reverseOrder())
使用Comparator 来排序一个list
list.stream().sorted(Comparator.comparing(Student::getAge))
把上面的元素逆序
list.stream().sorted(Comparator.comparing(Student::getAge).reversed())
当然还可以不用借助steam方式直接排序:
复制代码
list.sort(Comparator.comparing(Integer::intValue));
list.sort(Comparator.comparing(Integer::intValue).reversed());
list.sort(Comparator.comparing(Student::getAge));
list.sort(Comparator.comparing(Student::getAge).reversed());
查看链接
查看链接
第一种:使用谷歌Joiner方法
import com.google.common.base.Joiner;
public static String parseListToStr(List list){
String result = Joiner.on(",").join(list);
return result;
}
第二种:循环插入逗号
//java项目www.fhadmin.org
public static String parseListToStr(List list){
StringBuffer sb = new StringBuffer();
if(listIsNotNull(list)) {
for(int i=0;i<=list.size()-1;i++){
if(i
第三种:stream流
public static String parseListToStr3(List list){
String result = list.stream().map(String::valueOf).collect(Collectors.joining(","));
return result;
}
第四种:lambda表达式遍历并加入逗号
public static String parseListToStr2(List list){
StringBuffer sb = new StringBuffer();
list.stream().forEach(str->{
sb.append(str).append(",");
});
sb.deleteCharAt(sb.length()-1);
return sb.toString();
}