Find repeated items in a list

2

I have a LinkedList in java and I would like to store items that are repeated in the container in another container, How could I find out? Any clues?

public Set<Cancion> dameCancionesRepetidas(){
    SortedSet<Cancion> canciones = new TreeSet <Cancion>();
    /**CODIGO*/
    return canciones;
}

I have a container that we suppose has Song1, Song1, Song3, Song4, Song4.

Well, I want another container to return Song1, Song4, because they are the only ones that are repeated. I do not know if I explain myself well

    
asked by Juanma Perez 28.11.2016 в 19:09
source

2 answers

5

It can be done using the Streams API:

public static void main(String args[])
{
    LinkedList<String> canciones = new LinkedList<>();
    canciones.add("cancion1");
    canciones.add("cancion1");
    canciones.add("cancion3");
    canciones.add("cancion4");
    canciones.add("cancion4");

    List<String> duplicateList = 
        canciones
            .stream()
            // agrupar por cancion.
            .collect(Collectors.groupingBy(s -> s))
            .entrySet()
            .stream()
            // filtrar por los que tienen mas de una cancion por grupo
            .filter(e -> e.getValue().size() > 1)
            .map(e -> e.getKey())
            .collect(Collectors.toList());

    for(String cancion : duplicateList) {
        System.out.println(cancion);
    }
}

Result:

  

song4
  song1

Live demo .

The key part of the code is:

.collect(Collectors.groupingBy(s -> s))

... which groups the elements by song, and:

.filter(e -> e.getValue().size() > 1)

... that filters the results to groups that have more than one element, that is, those that have repeated songs.

You may have to adapt the code a little for your class Cancion , but the general idea should work well.

    
answered by 28.11.2016 / 20:28
source
1

This solution works for me:

//Lista que contienes las canciones
LinkedList<Object> lista = new LinkedList<>();

//Paso Strings para no enrollarme, pero funciona para cualquier Object
String obj1 = "Cancion1";
String obj2 = "Cancion2";
String obj3 = "Cancion3";

//Cargo la lista repitiendo 2
lista.add(obj1);
lista.add(obj2);
lista.add(obj2);  //REPETIDA 2ª VEZ
lista.add(obj3);
lista.add(obj2);  //REPETIDA 3ª VEZ
lista.add(obj3);  //REPETIDA 2ª VEZ

//Set para las repetidas - EMPIEZA EL BLOQUE QUE NECESITAS
Set<Object> cancionesRepetidas = new HashSet<Object>();
for(Object o : lista){
    //Si no coincide el primer y último index => están repetidas
    if(lista.indexOf(o) != lista.lastIndexOf(o))
        cancionesRepetidas.add(o);
}

System.out.println(cancionesRepetidas);

The output I get is:

  

[Song2, Song3]

NOTE: If you use a HashSet it will not give you problems with which it is not comparable what happens to you if you use a SortedSet and do not implement the interface

    
answered by 28.11.2016 в 19:49