Sheikh Rahman
Sheikh Rahman

Reputation: 915

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

    l1.add("Apple");
    l1.add("Orange");
    l1.add("Apple");
    l1.add("Milk");

    //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
        if(!(set).add(e)){
            System.out.println(e);
        }

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.

Upvotes: 4

Views: 2915

Answers (4)

shmosel
shmosel

Reputation: 50756

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

That is correct.

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.

set.add(e) attempts to add an element to the set, and it returns a boolean indicating whether it was added. Negating the result will cause new elements to be ignored and duplicates to be printed. Note that if an element is present 3 times it will be printed twice, and so on.

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<String> unique= new ArrayList<String>(new HashSet<String>(l1));

There are a number of ways to approach it. This one doesn't have the best performance but it's pretty straightforward:

for (int i = 0; i < l1.size(); i++) {
    boolean hasDup = false;
    for (int j = 0; j < l1.size(); j++) {
        if (i != j && l1.get(i).equals(l1.get(j))) {
            hasDup = true;
            break;
        }
    }
    if (!hasDup) {
        System.out.println(e);
    }
}

Upvotes: 3

With the /java8 power...

public static void main(String[] args) {
List<String> l1 = new ArrayList<>();

l1.add("Apple");
l1.add("Orange");
l1.add("Apple");
l1.add("Milk");

// remove duplicates
List<String> li = l1.parallelStream().distinct().collect(Collectors.toList());
System.out.println(li);

// map with duplicates frequency
Map<String, Long> countsList = l1.stream().collect(Collectors.groupingBy(fe -> fe, Collectors.counting()));
System.out.println(countsList);
// filter the map where only once 
List<String> l2 = countsList.entrySet().stream().filter(map -> map.getValue().longValue() == 1)
    .map(map -> map.getKey()).collect(Collectors.toList());
System.out.println(l2);
}

Upvotes: 1

xenteros
xenteros

Reputation: 15852

  1. You're right.
  2. Well... adding to the collection doesn't necessary need to return anything. Fortunately guys from the Sun or Oracle decided to return a message if the item was successfully added to the collection or not. This is indicated by true/false return value. true for a success.
  3. You can extend your current code with the following logic: if element wasn't added successfully to the set, it means it was a duplicate so add it to another set Set<> duplicates and later remove all duplicates from the Set.

Upvotes: 4

Sweeper
Sweeper

Reputation: 273988

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

l1.add("Apple");
l1.add("Orange");
l1.add("Apple");
l1.add("Milk");

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

for (String item : set) {
    if (l1.stream().filter(x -> !x.equals(item)).count() == l1.size() - 1) {
        System.out.println(item);
    }
}

Upvotes: 4

Related Questions