Java – get all rejected additions to set

I'm not very good at hashsets. I want to know if I can use them The addall method retrieves duplicates deleted by hashes So in my code, it asks the user to enter a value of up to 20, and if it is - 1, it interrupts Then delete the duplicates and display the completed list But now I want to display a list of deleted duplicates For example: 2 = 3 repetitions, 5 = 5 repetitions This is my code:

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.Scanner;
import java.util.Set;

public class Question {
    public static void main(String[] args) {
        ArrayList<Integer> entries = new ArrayList<Integer>();
        Scanner input = new Scanner(system.in);
        int counter = 0;
        int sentinel = -1;
        while (entries.size() <= 20) {

            System.out.println("Please enter some numbers into the entries list");
            entries.add(input.nextInt());
            if (entries.get(counter) == sentinel) {
                entries.remove(counter);
                break;
            }
            System.out.println("You've added: " + entries.get(counter) + ". So far your list is as shows: " + entries);
            counter++;

        }

        System.out.println("The list is: " + entries);
        System.out.println("Checking for Duplicates...");

        Set<Integer> num = new LinkedHashSet<>(entries);
        num.addAll(entries); // The addAll method deletes duplicates
        System.out.println(num);
        entries.clear();
        entries.addAll(num);

        System.out.println("The Finished list is: " + entries);

    }

}

Solution

Unfortunately, set does not track all items it rejects You must do this manually Quick and dirty methods are as follows:

Set<Integer> noDuplicates = new LinkedHashSet<Integer>();
List<Integer> rejects = new ArrayList<Integer>();
for(Integer entry : entry) {
   if(!noDuplicates.add(entry)) { rejects.add(entry) }
}

Note that when trying to add a duplicate element to the set, the add method returns false and rejects the add request

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>