• 一行代码实现java list去重


    1.不带类型写法:

    1
    List listWithoutDup = new ArrayList(new HashSet(listWithDup));

    2.带类型写法(以String类型为例):
    1)Java 7以下写法:

    1
    List<string> listWithoutDup = new ArrayList<string>(new HashSet<string>(listWithDup));</string></string></string>

    2)Java 7及以上写法:

    1
    List<string> listWithoutDup = new ArrayList<>(new HashSet<>(listWithDup));</string>


    样例:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    import java.util.ArrayList;
    import java.util.HashSet;
    import java.util.List;
     
    public class Test {
        public static void main(String[] args) {
            List<string> listWithDup = new ArrayList<string>();
            listWithDup.add("1");
            listWithDup.add("2");
            listWithDup.add("3");
            listWithDup.add("1");
     
            List<string> listWithoutDup = new ArrayList<string>(new HashSet<string>(listWithDup));
            System.out.println("list with dup:"+ listWithDup);
            System.out.println("list without dup:"+ listWithoutDup);
        }
    }</string></string></string></string></string>

    样例运行结果: list with dup:[1, 2, 3, 1]
    list without dup:[3, 2, 1]

  • 相关阅读:
    office的高级应用
    python基础
    maven 资源导出失败问题
    单向环形链表和约瑟夫问题
    JDBC连接MySQL
    环形队列
    稀疏数组
    数据库锁机制和事务隔离级别总结
    context的简单应用
    JDBC基本使用方法
  • 原文地址:https://www.cnblogs.com/kungfupanda/p/6252825.html
Copyright © 2020-2023  润新知