?如果list中裝的是簡單元素,int 類型,string類型,想要去重,并且保持在list中的順序,最快的方式如下:
使用 LinkedHashSet,去重加有序。
使用 HashSet,只去重,但順序任意。
public static void t1(){
List<Integer> list = new ArrayList<>(Arrays.asList(1, 1, 2, 2, 3, 3, 4, 5, 6, 6, 7, 8));
System.out.println(list); //輸出[10, 1, 1, 2, 2, 3, 3, 4, 5, 6, 6, 7, 8]
LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>(list);
List<Integer> distinct = new ArrayList<>(linkedHashSet);
System.out.println(distinct); //輸出[10, 1, 2, 3, 4, 5, 6, 7, 8]
}
public static void t2(){
List<String> list = new ArrayList<>(Arrays.asList("張三","張三", "李四", "李四", "tom", "tom", "mike"));
System.out.println(list); //[張三, 張三, 李四, 李四, tom, tom, mike]
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>(list);
List<String> distinct = new ArrayList<>(linkedHashSet);
System.out.println(distinct); //[張三, 李四, tom, mike]
}
參考文章來源:http://www.zghlxwxcb.cn/news/detail-545274.html
Java中List集合對象去重及按屬性去重的8種方法_java list對象去重_//承續(xù)緣_紀(jì)錄片的博客-CSDN博客文章來源地址http://www.zghlxwxcb.cn/news/detail-545274.html
到了這里,關(guān)于java list 快速去重 有序 重復(fù) LinkedHashSet HashSet的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!