后端——》Java-stream的一些应用

1,将一个list中map的值根据key取出来组成另一个list
eg:假如map中有id这个key
List<Map> requirementsList=new ArrayList<>();
List<Long> newList=requirementsList.stream().map(paramap -> StringUtil.safeToInteger(paramap.get("id"), 0).longValue()).collect(Collectors.toList());

2,将一个list中实体的属性取出来组成另一个list;
eg:假如Studnet实体有nane这个属性
List<Student> requirementsList=new ArrayList<>();
List<String> newList=requirementsList.stream().map(student ->student::name).collect(Collectors.toList());

3,将一个list中实体的某个字段取出来逗号拼接
eg:假如Studnet实体有nane这个属性
List<Student> requirementsList=new ArrayList<>();
String names=requirementsList.stream().map(student ->student::name).collect(Collectors.joining(","));

4,将一个list中按照实体的字段过滤
eg:假如Studnet实体有nane这个属性,根据name去重
List<Student> requirementsList=new ArrayList<>();
requirementsList=requirementsList.stream().filter(distinctByKey(student ->student::name)).collect(Collectors.toList());
 
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Map<Object,Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }
5,还有其他很多用法
 /*在括号中student ->student::name和student ->student.getName()是一个意思。都可以用*/

 

 

实际案例:

将两个list合并成为一个新的list并分组,如下:

list1:
[{班级:一班,学生:张三},{班级:二班,学生:李四}]
list2:
[{班级:一班,教师:小明},{班级:二班,教师:小红}]
合并后list:
[{班级:一班,学生:张三,教师:小明},{班级:二班,学生:李四,教师:小红}]

实现方式如下:

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class TestController {
    private static final Logger LOGGER = LoggerFactory.getLogger(TestController.class);

    /*先制造测试数据*/
    public static List<Map<String,String>>  classStudentList=new ArrayList();
    public static List<Map<String,String>>  classTeacherList=new ArrayList();

    public static Map<String,String> classStudent1=new HashMap();
    public static Map<String,String> classStudent2=new HashMap();

    public static Map<String,String> classTeacher1=new HashMap();
    public static Map<String,String> classTeacher2=new HashMap();
    static {
        classStudent1.put("班级","一班");
        classStudent1.put("学生","张三");
        classStudent2.put("班级","二班");
        classStudent2.put("学生","李四");
        classStudentList.add(classStudent1);
        classStudentList.add(classStudent2);

        classTeacher1.put("班级","一班");
        classTeacher1.put("教师","小明");
        classTeacher2.put("班级","二班");
        classTeacher2.put("教师","小红");
        classTeacher2.put("班级","三班");
        classTeacher2.put("教师","小蓝");
        classTeacherList.add(classTeacher1);
        classTeacherList.add(classTeacher2);
    }

    public static void main(String[] a){
        /*list合并*/
        List<Map<String,String>> allList= Stream.of(classStudentList, classTeacherList).flatMap(Collection::stream).collect(Collectors.toList());
        LOGGER.info("合并后的list:{}",JSON.toJSONString(allList));

        /*list转map*/
        Map<String, List<Map<String, String>>> classMap=allList.stream().collect(Collectors.groupingBy(e -> e.get("班级")));
        LOGGER.info("分组后的list:{}",JSON.toJSONString(classMap));

        /*map提取元素重组list*/
        List<Map<String,String>> classList2 = classMap.entrySet().stream().map(e->{
            Map<String, String> map = new HashMap<>();
            map.put("学生",e.getValue().stream().map(f->f.get("学生")!=null?f.get("学生"):"").collect(Collectors.joining()));
            map.put("教师",e.getValue().stream().map(f->f.get("教师")!=null?f.get("教师"):"").collect(Collectors.joining()));
            map.put("班级",e.getKey());
            return map;
        }).collect(Collectors.toList());
        LOGGER.info("拼接板结果list:{}",JSON.toJSONString(classList2));

        /*将以上三步合为1步*/
        List<Map<String,String>> classList=Stream.of(classStudentList, classTeacherList)
                .flatMap(Collection::stream)
                .collect(Collectors.toList())
                .stream().collect(Collectors.groupingBy(e -> e.get("班级")))
                .entrySet().stream().map(e->{
                    Map<String, String> map = new HashMap<>();
                    map.put("学生",e.getValue().stream().map(f->f.get("学生")!=null?f.get("学生"):"").collect(Collectors.joining()));
                    map.put("教师",e.getValue().stream().map(f->f.get("教师")!=null?f.get("教师"):"").collect(Collectors.joining()));
                    map.put("班级",e.getKey());
                    return map;
                })
                .collect(Collectors.toList());
        LOGGER.info("终极版结果list:{}",JSON.toJSONString(classList));
    }
}

 

打印的日志如下

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值