Skip to content

动态去重

快速开始

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class App {
    public static void main(String[] args) {
        // 查询所需列
        List<String> fields = List.of("col_1", "col_2");

        // 查询所需数据
        List<Map<String, String>> records = List.of(
            Map.of("col_1", "张三", "col_2", "罗翔", "col_3", "1", "col_4", "A"),
            Map.of("col_1", "张三", "col_2", "罗翔", "col_3", "2", "col_4", "B"),
            Map.of("col_1", "张三", "col_2", "罗翔", "col_3", "3", "col_4", "C")
        );

        // 动态去重
        List<Map<String, String>> result = records.stream().map(record -> {
            Map<String, String> newRecord = new HashMap<>();
            record.forEach((k, v) -> {
                if (fields.contains(k)) {
                    newRecord.put(k, v);
                }
            });
            return newRecord;
        }).distinct().collect(Collectors.toList());

        System.out.println(result);
    }
}