zoukankan      html  css  js  c++  java
  • 使用Lambda给List集合去重

    实体类

    class Student {
    
        private String studentName;
        private Integer studentAge;
    
        public Student() {
        }
    
        public Student(String studentName, Integer studentAge) {
            this.studentName = studentName;
            this.studentAge = studentAge;
        }
    
        public String getStudentName() {
            return studentName;
        }
    
        public void setStudentName(String studentName) {
            this.studentName = studentName;
        }
    
        public Integer getStudentAge() {
            return studentAge;
        }
    
        public void setStudentAge(Integer studentAge) {
            this.studentAge = studentAge;
        }
    }
    

    去重

    	List<Student> list = new ArrayList<>();
            Collections.addAll(list, new Student("张三", 18), new Student("李四", 18), new Student("张三", 18));
            list =
                    list.stream()
                            .collect(
                                    Collectors.collectingAndThen(
                                            Collectors.toCollection(
                                                    () -> new TreeSet<>(Comparator.comparing(Student::getStudentName))),
                                            ArrayList::new));
            list.forEach(student -> System.out.println(student.getStudentName() + ":" + student.getStudentAge()));
    		// 输出:
    			// 张三:18
    			// 李四:18
    

    方法二

    @Test
    public void duplicateKey() {
    	List<String> list = new LinkedList<>();
    	Collections.addAll(list, "apple", "pear", "banana", "banana");
    
    	System.out.println("原始List: " + JSON.toJSON(list));
    
    	Map<String, String> map = list.stream().
    			collect(Collectors.
    					toMap(item -> item, item -> item, (item1, item2) -> item1));
    
    	list.clear();
    	// TODO: 使用Map集合value不可重复的特征, 给List集合去重
    	map.forEach((k, v) -> list.add(v));
    
    	System.out.println("去重List: " + JSON.toJSON(list));
    }
    
  • 相关阅读:
    Docker 版本升级
    Docker Swarm 常用命令
    Docker Swarm 介绍 or 工作原理
    Docker OpenvSwitch 应用部署
    Docker OpenvSwitch 介绍 or 工作原理
    Solr配置与简单Demo[转]
    使用solrj操作solr索引库,solr是lucene服务器
    Apache Solr配置
    使用solr搭建你的全文检索
    [转]flume-ng+Kafka+Storm+HDFS 实时系统搭建
  • 原文地址:https://www.cnblogs.com/Twittery/p/14388009.html
Copyright © 2011-2022 走看看