简体   繁体   中英

How to create a unique list of values in Java?

I am trying to create a list, which only consists of unique values.

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 );

What I expect as an output is: 6,8,0. So, if duplicates exist, I want to delete both of them. The HashSet only removes the duplicates, so that each value only occurs once. However, I want to remove both the numbers, so that I end up with a list, which only has the numbers that occur once in the original list.

One solution would be to build a frequency Map and only retain the keys whose value equals 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()));

One possible value of this List is:

[0, 6, 8]

Another possiblilty with Stream 's:

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

Which will create a filter out all the elements that occur more than once using Collections::frequency . Which returns the List :

[6, 8, 0]

One other possible solution is collecting the list data into set and then get back to list again.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM