Finding duplicates and not duplicates in Java

I know that this question has been answered “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 does not work, because List allows duplication, and HashSet is the correct assumption?

Question 2: What does this line mean: if (! (Set) .add (e)) In the for loop we check if the line St is in the list l1, and then what does this line do if (! (Set) .add (e))

This code will print the apple as a result, as this is a duplicate value.

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

Thanks in advance for your time.

+4
4

1) , . .

2) add HashSet false, . , .

3) , , , 1. ( ! , -.)

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);
    }
}
+3
  • .
  • ... , . , Sun Oracle , . true/false. true .
  • : , , , Set<> duplicates, duplicates Set.
+4

1: , List , HashSet - ?

.

2: : if (! (set).add(e)) for , s l1, , , (! ( ).add())

, .

set.add(e) , boolean, , . . , 3 , ..

3: , , Apple? , Apple. List<String> unique= new ArrayList<String>(new HashSet<String>(l1));

. , :

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

/java 8...

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

Source: https://habr.com/ru/post/1660118/


All Articles