Backend- "Algunas aplicaciones de Java-stream

1. Saque el valor del mapa en una lista de acuerdo con la clave para formar otra lista,
por ejemplo: Si la clave es id en el mapa
List <Map> requirementsList = new ArrayList <> ();
List <Long> newList = requirementsList .stream () .map (paramap -> StringUtil.safeToInteger (paramap.get ("id"), 0) .longValue ()). collect (Collectors.toList ());

2. Saque los atributos de las entidades en una lista para formar otra lista;
por ejemplo: si la entidad Studnet tiene el atributo de nane,
List <Student> requirementsList = new ArrayList <> ();
List <String> newList = requirementsList.stream (). map (estudiante -> estudiante :: nombre) .collect (Collectors.toList ());

3, Saque un cierto campo de la entidad en una lista para empalmar con comas,
por ejemplo: Si la entidad Studnet tiene el atributo de nane
List <Student> requirementsList = new ArrayList <> ();
String names = requirementsList.stream (). Map (estudiante-> estudiante :: nombre) .collect (Collectors.joining (","));

4. Filtre una lista según el campo de la entidad,
por ejemplo: Si la entidad Studnet tiene el atributo nane, elimine los duplicados según el nombre
List <Student> requirementsList = new ArrayList <> ();
requirementsList = requirementsList.stream () .filter (differentByKey (estudiante -> estudiante :: nombre)). collect (Collectors.toList ());
 
public static <T> Predicate <T> differentByKey (Function <? super T,?> keyExtractor) {         Map <Object, Boolean> seen = new ConcurrentHashMap <> ();         return t -> seen.putIfAbsent (keyExtractor.apply (t), Boolean.TRUE) == null;     } 5, hay muchos otros usos  / * entre paréntesis estudiante -> estudiante :: nombre y alumno -> alumno.getName () es un significado. Puede ser usado*/




 

 

caso real:

Combine las dos listas en una nueva lista y agrúpelas de la siguiente manera:

list1:
[{Clase: Clase uno, Estudiante: Zhang San}, {Clase: Clase dos, Estudiante: Li Si}]
list2:
[{Clase: Clase uno, Maestro: Xiao Ming}, {Clase: Clase dos, Maestro: Small Red}]
lista combinada:
[{Clase: Clase uno, Estudiante: Zhang San, Maestro: Xiao Ming}, {Clase: Clase dos, Estudiante: Li Si, Maestra: Xiao Hong}]

La implementación es la siguiente:

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));
    }
}

 

El registro impreso es el siguiente

 

Supongo que te gusta

Origin blog.csdn.net/nienianzhi1744/article/details/98206409
Recomendado
Clasificación