Как найти повторяющиеся элементы в списке java

If your elements are somehow Comparable (the fact that the order has any real meaning is indifferent — it just needs to be consistent with your definition of equality), the fastest duplicate removal solution is going to sort the list ( 0(n log(n)) ) then to do a single pass and look for repeated elements (that is, equal elements that follow each other) (this is O(n)).

The overall complexity is going to be O(n log(n)), which is roughly the same as what you would get with a Set (n times long(n)), but with a much smaller constant. This is because the constant in sort/dedup results from the cost of comparing elements, whereas the cost from the set is most likely to result from a hash computation, plus one (possibly several) hash comparisons. If you are using a hash-based Set implementation, that is, because a Tree based is going to give you a O( n log²(n) ), which is even worse.

As I understand it, however, you do not need to remove duplicates, but merely test for their existence. So you should hand-code a merge or heap sort algorithm on your array, that simply exits returning true (i.e. «there is a dup») if your comparator returns 0, and otherwise completes the sort, and traverse the sorted array testing for repeats. In a merge or heap sort, indeed, when the sort is completed, you will have compared every duplicate pair unless both elements were already in their final positions (which is unlikely). Thus, a tweaked sort algorithm should yield a huge performance improvement (I would have to prove that, but I guess the tweaked algorithm should be in the O(log(n)) on uniformly random data)

I did a similiar program that shows you the words that where repeated in an ArrayList (also it shows the arraylist content and the larger string)

Oh, by the way, variables, and other stuff like comments are in spanish, cause I speak spanish:/ but, if you see the code you can see that I resolved the problem with 2 bucles for!

public void mostrarDiecisiete() {


        ArrayList<String> array = new ArrayList<String>();

        ArrayList<String> array2 = new ArrayList<String>();

        Scanner sc = new Scanner(System.in);

        String sss = "";

        System.out.println("");

        while (!sss.equalsIgnoreCase("fin")) {

            System.out.print("Ingrese un string: ");
            sss = sc.nextLine();
            if (!sss.equalsIgnoreCase("fin")) {
                array.add(sss);
            }
        }

        int mayor = 0;
        Iterator it = array.iterator();
        String s = "";
        boolean repetir = true;
        int j = 0;
        for (int i = 0; i < array.size(); i++) {
            System.out.println("");
            System.out.print("Posicion: " + i + " del array: " + array.get(i) + " " + "n");

            if (array.get(i).length() > mayor) {

                mayor = array.get(i).length();

                s = array.get(i);

            }
        }

        for (int i = 0; i < array.size(); i++) {


            System.out.println("vuelta nro: " + i + " del primer for");
            if(j==array.size()){

                j=0;//inicializa de nuevo j en cero si j alcanzo el tamaño del array
                j=i;//inicializa j en el numero de vuelta del primer for, para luego sumarle uno mas asi siempre compara con el siguiente
            }
            for (j++; j < array.size(); j++) {//empieza a comparar con uno mas adelante siempre

                if (array.get(i).equalsIgnoreCase(array.get(j))) {//si el array de la posicion i se repite entre la 1 y la ultima de la pos j

                    System.out.println("el string " + array.get(i) + " se repite en la posicion " + j);

                    array2.add(array.get(i)); // se agrega a array2



                } else {
                    System.out.println("String: " + array.get(i) + " no se repite con la posicion " + j);



                }
            }

        }

        System.out.println("");

        System.out.print(
                "el array es: " + array);

        System.out.println(
                "");

        System.out.println(
                "El array mas largo es: " + s + " y tiene " + mayor + " caracteres");

        System.out.println(
                "");

        System.out.println(
                "Los Strings repetidos son" + array2);

    }

}

This is my output:

Ingrese un string: vaca
Ingrese un string: perro
Ingrese un string: dinosaurio
Ingrese un string: gato
Ingrese un string: cebra
Ingrese un string: DiNoSauRiO
Ingrese un string: VACA
Ingrese un string: hamster
Ingrese un string: gato
Ingrese un string: canario
Ingrese un string: elefante
Ingrese un string: tortuga
Ingrese un string: fin

Posicion: 0 del array: vaca 

Posicion: 1 del array: perro 

Posicion: 2 del array: dinosaurio 

Posicion: 3 del array: gato 

Posicion: 4 del array: cebra 

Posicion: 5 del array: DiNoSauRiO 

Posicion: 6 del array: VACA 

Posicion: 7 del array: hamster 

Posicion: 8 del array: gato 

Posicion: 9 del array: canario 

Posicion: 10 del array: elefante 

Posicion: 11 del array: tortuga 

vuelta nro: 0 del primer for

String: vaca no se repite con la posicion 1
String: vaca no se repite con la posicion 2
String: vaca no se repite con la posicion 3
String: vaca no se repite con la posicion 4
String: vaca no se repite con la posicion 5
el string vaca se repite en la posicion 6
String: vaca no se repite con la posicion 7
String: vaca no se repite con la posicion 8
String: vaca no se repite con la posicion 9
String: vaca no se repite con la posicion 10
String: vaca no se repite con la posicion 11
vuelta nro: 1 del primer for
String: perro no se repite con la posicion 2
String: perro no se repite con la posicion 3
String: perro no se repite con la posicion 4
String: perro no se repite con la posicion 5
String: perro no se repite con la posicion 6
String: perro no se repite con la posicion 7
String: perro no se repite con la posicion 8
String: perro no se repite con la posicion 9
String: perro no se repite con la posicion 10
String: perro no se repite con la posicion 11
vuelta nro: 2 del primer for
String: dinosaurio no se repite con la posicion 3
String: dinosaurio no se repite con la posicion 4
el string dinosaurio se repite en la posicion 5
String: dinosaurio no se repite con la posicion 6
String: dinosaurio no se repite con la posicion 7
String: dinosaurio no se repite con la posicion 8
String: dinosaurio no se repite con la posicion 9
String: dinosaurio no se repite con la posicion 10
String: dinosaurio no se repite con la posicion 11
vuelta nro: 3 del primer for
String: gato no se repite con la posicion 4
String: gato no se repite con la posicion 5
String: gato no se repite con la posicion 6
String: gato no se repite con la posicion 7
el string gato se repite en la posicion 8
String: gato no se repite con la posicion 9
String: gato no se repite con la posicion 10
String: gato no se repite con la posicion 11
vuelta nro: 4 del primer for
String: cebra no se repite con la posicion 5
String: cebra no se repite con la posicion 6
String: cebra no se repite con la posicion 7
String: cebra no se repite con la posicion 8
String: cebra no se repite con la posicion 9
String: cebra no se repite con la posicion 10
String: cebra no se repite con la posicion 11
vuelta nro: 5 del primer for
String: DiNoSauRiO no se repite con la posicion 6
String: DiNoSauRiO no se repite con la posicion 7
String: DiNoSauRiO no se repite con la posicion 8
String: DiNoSauRiO no se repite con la posicion 9
String: DiNoSauRiO no se repite con la posicion 10
String: DiNoSauRiO no se repite con la posicion 11
vuelta nro: 6 del primer for
String: VACA no se repite con la posicion 7
String: VACA no se repite con la posicion 8
String: VACA no se repite con la posicion 9
String: VACA no se repite con la posicion 10
String: VACA no se repite con la posicion 11
vuelta nro: 7 del primer for
String: hamster no se repite con la posicion 8
String: hamster no se repite con la posicion 9
String: hamster no se repite con la posicion 10
String: hamster no se repite con la posicion 11
vuelta nro: 8 del primer for
String: gato no se repite con la posicion 9
String: gato no se repite con la posicion 10
String: gato no se repite con la posicion 11
vuelta nro: 9 del primer for
String: canario no se repite con la posicion 10
String: canario no se repite con la posicion 11
vuelta nro: 10 del primer for
String: elefante no se repite con la posicion 11
vuelta nro: 11 del primer for

el array es: [vaca, perro, dinosaurio, gato, cebra, DiNoSauRiO, VACA, hamster, gato, canario, elefante, tortuga]

El array mas largo es: dinosaurio y tiene 10 caracteres

Los Strings repetidos son[vaca, dinosaurio, gato]  

BUILD SUCCESSFUL (total time: 2 minutes 48 seconds)

В этом посте будет обсуждаться, как идентифицировать дубликаты в списке в Java.

1. Использование Set

Простое решение состоит в том, чтобы перебрать все значения в списке и вставить каждый элемент в список. HashSet. Если текущий элемент уже существует в наборе, то это дубликат. Вы можете собрать все найденные дубликаты в новый список.

Это можно легко сделать с помощью Java 8 Stream. Обратите внимание, что решение использует возвращаемое значение Set.add() метод, чтобы определить, присутствует ли значение уже в наборе или нет

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

import java.util.HashSet;

import java.util.List;

import java.util.Set;

import java.util.stream.Collectors;

class Main

{

    private static <T> Set<T> findDuplicates(List<T> list)

    {

        Set<T> seen = new HashSet<>();

        return list.stream()

                .filter(e -> !seen.add(e))

                .collect(Collectors.toSet());

    }

    public static void main(String[] args) {

        List<Integer> values = List.of(1, 3, 2, 3, 4, 1);

        Set<Integer> duplicates = findDuplicates(values);

        System.out.println(duplicates);

    }

}

Скачать  Выполнить код

результат:

[1, 3]

 
Приведенный выше код эквивалентен следующему коду (для Java 7 и ниже):

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

import java.util.HashSet;

import java.util.List;

import java.util.Set;

class Main

{

    private static <T> Set<T> findDuplicates(Iterable<T> iterable)

    {

        Set<T> duplicates = new HashSet<>();

        Set<T> seen = new HashSet<>();

        for (T t : iterable) {

            if (!seen.add(t)) {

                duplicates.add(t);

            }

        }

        return duplicates;

    }

    public static void main(String[] args) {

        List<Integer> values = List.of(1, 3, 2, 3, 4, 1);

        Set<Integer> duplicates = findDuplicates(values);

        System.out.println(duplicates);

    }

}

Скачать  Выполнить код

результат:

[1, 3]

2. Использование Collections.frequency() метод

Самый простой способ, вероятно, состоит в том, чтобы подсчитать частоту каждого элемента списка, чтобы определить, является ли он дубликатом или нет. Вы можете использовать Collections.frequency() метод для этого, который возвращает количество элементов в коллекции.

Вот код, использующий Stream API:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

import java.util.Collections;

import java.util.List;

import java.util.Set;

import java.util.stream.Collectors;

class Main

{

    private static <T> Set<T> findDuplicates(List<T> list)

    {

        return list.stream().distinct()

                .filter(i -> Collections.frequency(list, i) > 1)

                .collect(Collectors.toSet());

    }

    public static void main(String[] args) {

        List<Integer> values = List.of(1, 3, 2, 3, 4, 1);

        Set<Integer> duplicates = findDuplicates(values);

        System.out.println(duplicates);

    }

}

Скачать  Выполнить код

результат:

[1, 3]

 
Это эквивалентно следующему:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

import java.util.Collections;

import java.util.HashSet;

import java.util.List;

import java.util.Set;

class Main

{

    private static <T> Set<T> findDuplicates(List<T> list)

    {

        Set<T> set = new HashSet<>();

        for (T i : list) {

            if (Collections.frequency(list, i) > 1) {

                set.add(i);

            }

        }

        return set;

    }

    public static void main(String[] args) {

        List<Integer> values = List.of(1, 3, 2, 3, 4, 1);

        Set<Integer> duplicates = findDuplicates(values);

        System.out.println(duplicates);

    }

}

Скачать  Выполнить код

результат:

[1, 3]

3. Использование Collectors.groupingBy() функция

Приведенное выше решение вызывает Collections.frequency() метод для каждого элемента списка. Лучшее решение — создать карту частот и использовать ее, чтобы определить, дублируется ли элемент или нет. В следующем решении Java 8 потоки используются для фильтрации элементов с частотой более 1:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

import java.util.List;

import java.util.Map;

import java.util.Set;

import java.util.function.Function;

import java.util.stream.Collectors;

class Main

{

    private static <T> Set<T> findDuplicates(List<T> list)

    {

        Map<T, Long> frequencyMap = list.stream()

                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        return frequencyMap.keySet().stream()

                .filter(key -> frequencyMap.get(key) > 1)

                .collect(Collectors.toSet());

    }

    public static void main(String[] args) {

        List<Integer> values = List.of(1, 3, 2, 3, 4, 1);

        Set<Integer> duplicates = findDuplicates(values);

        System.out.println(duplicates);

    }

}

Скачать  Выполнить код

результат:

[1, 3]

Это все, что касается выявления дубликатов в списке в Java.

Иногда требуется найти дубликаты в существующем списке. Например, это может быть список строк или чисел. Это довольно легко сделать методом перебора.

Решение

Сперва объявим коллекцию для хранения дублирующихся значений. В качестве такой коллекции лучше взять HashSet. Эта коллекция сама по себе не будет содержать дубликатов.

Set<E> duplicates = new HashSet<>();

Затем мы будем в одном цикле проходить по всем элементам массива, брать каждый элемент и сравнивать его со всеми остальными элементами (но уже во втором цикле):

for (int i = 0; i < a.size(); i++) {
    E e1 = a.get(i);
    if (e1 == null) continue; // игнорируем null

    // сравниваем каждый элемент со всеми остальными
    for (int j = 0; j < a.size(); j++) {
        if (i == j) continue; // не проверяем элемент с собой же
        E e2 = a.get(j);
        if (e1.equals(e2)) {
            // дубликат найден, сохраним его
            duplicates.add(e2);
        }
    }
}

После этого возвратим список дубликатов:

return new ArrayList<>(duplicates);

Проверка программы

List<String> animals = Arrays.asList("cat", "dog", "cow", "sheep", "cat", "dog");

System.out.println("Входной массив: " + animals);
System.out.println("Дубликаты: " + getDuplicatesWithIteration(animals));

Исходный код

package ru.javalessons.arrays;

import java.util.*;

public class ListFindDuplicates {
    public static void main(String[] args) {
        List<String> animals = Arrays.asList("cat", "dog", "cow", "sheep", "cat", "dog");

        System.out.println("Входной массив: " + animals);
        System.out.println("Дубликаты: " + getDuplicatesWithIteration(animals));
    }

    public static <E> List<E> getDuplicatesWithIteration(List<E> a) {
        Set<E> duplicates = new HashSet<>();
        for (int i = 0; i < a.size(); i++) {
            E e1 = a.get(i);
            if (e1 == null) continue; // игнорируем null

            // сравниваем каждый элемент со всеми остальными
            for (int j = 0; j < a.size(); j++) {
                if (i == j) continue; // не проверяем элемент с собой же
                E e2 = a.get(j);
                if (e1.equals(e2)) {
                    // дубликат найден, сохраним его
                    duplicates.add(e2);
                }
            }
        }
        return new ArrayList<>(duplicates);
    }
}

Заключение

Довольно простым методом перебора можно найти дубликаты в списке.

Чтобы обнаружить повторяющегося значения в примитивном массиве Java, вам нужно сравнить каждый элемент массива со всеми оставшимися, в случае совпадения получим дублированный элемент.

Одно из решений для этого – использовать два цикла (вложенных), где внутренний цикл начинается с i + 1 (где i – переменная внешнего цикла), чтобы избежать повторений в сравнении.

Пример

import java.util.Arrays;
import java.util.Scanner;

public class DetectDuplcate {
   
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the size of the array that is to be created::");
      int size = sc.nextInt();
      int[] myArray = new int[size];
      System.out.println("Enter the elements of the array ::");
   
      for(int i=0; i<size; i++) {
         myArray[i] = sc.nextInt();
      }
      System.out.println("The array created is ::"+Arrays.toString(myArray));
      System.out.println("indices of the duplicate elements :: ");
   
      for(int i=0; i<myArray.length; i++) {
         for (int j=i+1; j<myArray.length; j++) {
            if(myArray[i] == myArray[j]) {
               System.out.println(j);
            }
         }
      }
   }
}

Итог

Enter the size of the array that is to be created ::
6
Enter the elements of the array ::
87
52
87
63
41
63
The array created is :: [87, 52, 87, 63, 41, 63]
indices of the duplicate elements ::
2
5

Способ 2

В дополнение к этому у нас есть более надежное решение. Набор интерфейсов не позволяет дублировать элементы, поэтому создайте объект set и попробуйте добавить каждый элемент к нему с помощью метода add(), в случае повторения элементов этот метод возвращает false:

import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class DetectDuplcateUsingSet {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the size of the array that is to be created::");
      int size = sc.nextInt();
      int[] myArray = new int[size];
      System.out.println("Enter the elements of the array ::");

      for(int i=0; i<size; i++) {
         myArray[i] = sc.nextInt();
      }
      System.out.println("The array created is ::"+Arrays.toString(myArray));
      System.out.println("indices of duplicate elements in the array are elements::");
      Set set = new HashSet();
 
      for(int i=0; i<myArray.length; i++) {
         if(!set.add(myArray[i])) {
            System.out.println(i);
         }
      }
   }
}

Результат

Enter the size of the array that is to be created ::
5
Enter the elements of the array ::
78
56
23
78
45
The array created is :: [78, 56, 23, 78, 45]
indices of duplicate elements in the array are elements::
3

Понравилась статья? Поделить с друзьями:

Не пропустите также:

  • Как найти диф функции
  • Как составить свой план сочинения
  • Как найти объем жидкости в кубических сантиметрах
  • Как найти кварц в astroneer
  • Как нашли второго летчика

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии