java List集合去重保持原順序


  • LinkedHashSet去重,去重后保持原有順序(重復數據只保留一條)

    String[] arr = new String[] { "a", "c", "aa", "a", "b", "d" };
    // 利用LinkedHashSet去重
    Collection collection = new LinkedHashSet(Arrays.asList(arr));
    System.out.println("(LinkedHashSet) distinct words: " + collection);
    // 轉為list
    List list = new ArrayList(collection);
    

    輸出:

    (LinkedHashSet) distinct words: [a, c, aa, b, d]

  • HashSet去重方法,去重后順序打亂(重復數據只保留一條)

    String[] arr = new String[] { "a", "c", "aa", "a", "b", "d" };
    // 利用HashSet去重
    HashSet h = new HashSet(Arrays.asList(arr));
    System.out.println("(HashSet) distinct words: " + collection);
    // 轉為list
    List list2 = new ArrayList(collection);
    

    輸出:

    (HashSet) distinct words: [a, c, aa, b, d]


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。