1

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.

0

3 Answers 3

3

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]
Sign up to request clarification or add additional context in comments.

4 Comments

Ah, you beat me to it by like 5 seconds!
@flakes I can't tell you how many times that's happened to me!
what if i want to print the output? Can i use an ArrayList instead of an array?
@user8231110 The above code returns a List. If you want an ArrayList specifically, then you'll need to change the Collector to Collectors.toCollection(ArrayList::new).
2

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]

1 Comment

O(n^2) time complexity. Should opt for a different solution. Many duplicates can result in many redundant calls to Collections.frequency
-1

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

1 Comment

The OP already shows this sort of thing in the original post. This will remove duplicates but that's not what the OP is trying to do. They are trying to remove completely any and all items that have more than one entry, a greater trimming than just duplicates.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.