簡體   English   中英

如何在Java中創建唯一的值列表?

[英]How to create a unique list of values in Java?

我正在嘗試創建一個僅包含唯一值的列表。

String[] arr = {"5", "5", "7", "6", "7", "8", "0"};
    List<String> uniqueList = new ArrayList<String>(new HashSet<String>( Arrays.asList(arr) ));
    System.out.println( uniqueList );

我期望的輸出是:6,8,0。 因此,如果存在重復項,我想將它們都刪除。 HashSet僅刪除重復項,因此每個值僅出現一次。 但是,我想同時刪除兩個數字,以便最終得到一個列表,該列表僅具有在原始列表中出現一次的數字。

一種解決方案是構建一個頻率Map並且僅保留值等於1的鍵:

String[] arr = {"5", "5", "7", "6", "7", "8", "0"};

Arrays.stream(arr)
      .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
      .entrySet()
      .stream()
      .filter(e -> e.getValue() == 1)
      .map(Map.Entry::getKey)
      .collect(Collectors.toList()));

List一個可能值為:

[0, 6, 8]

Stream的另一個可能性:

List<String> arr1 = Arrays.asList(arr).stream()
                   .filter(i -> Collections.frequency(Arrays.asList(arr), i)  < 2)
                   .collect(Collectors.toList());
arr1.forEach(System.out::println);

這將使用Collections::frequency過濾出所有出現多次的所有元素。 返回List

[6, 8, 0]

另一種可能的解決方案是將列表數據收集到集合中,然后再次返回列表。

String[] arr = {"5", "5", "7", "6", "7", "8", "0"};

List<String> stringList = Arrays.stream(arr).collect(Collectors.toSet()).stream().collect(Collectors.toList());

for (String s : stringList) {
     System.out.println(s);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM