Sheikh Rahman Sheikh Rahman - 1 year ago 115
Java Question

Finding duplicate and non duplicate in Java

I know this question has been answered on "how to find" many times, however I have a few additional questions. Here is the code I have

public static void main (String [] args){

List<String> l1= new ArrayList<String>();


//List<String> l2=new ArrayList<String>();
//HashSet is a good choice as it does not allow duplicates
HashSet<String> set = new HashSet<String>();

for( String e: l1){

//if(!(l2).add(e)) -- did not work

Question 1:The list did not work because List allows Duplicate while HashSet does not- is that correct assumption?

Question 2: What does this line mean: if(!(set).add(e))
In the for loop we are checking if String e is in the list l1 and then what does this line validates if(!(set).add(e))

This code will print apple as output as it is the duplicate value.

Question 3: How can i have it print non Duplicate values, just Orange and Milk but not Apple? I tried this approach but it still prints Apple.
List unique= new ArrayList(new HashSet(l1));

Thanks in advance for your time.

Answer Source

1) Yes that is correct. We often use sets to remove duplicates.

2) The add method of HashSet returns false when the item is already in the set. That's why it is used to check whether the item exists in the set.

3) To do this, you need to count up the number of occurrances of each item in the array, store them in a hash map, then print out those items that has a count of 1. Or, you could just do this (which is a little dirty and is slower! However, this approach takes a little less space than using a hash map.)

List<String> l1= new ArrayList<>();


HashSet<String> set = new HashSet<>(l1);

for (String item : set) {
    if ( -> !x.equals(item)).count() == l1.size() - 1) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download