Compare two lists and delete repeated

0

I have two string lists

  • listA = {a, b, c}
  • listB = {e, a, b, d, c}
  • I want to have a single list with all the elements without any repeated,

    Example: listFinal = {a,b,c,d,e},

    I've done it by doing this:

     listB.removeAll(listA);
        listA.addAll(listB);
    

    But I would like to do it without those functions, something of recursion maybe what would the code be like?

        
    asked by goku venz 16.08.2018 в 19:31
    source

    2 answers

    0

    You can combine the two lists in a HashSet . In that case, the duplicates will be eliminated and the elements will be ordered without any additional manipulation.

    Sample code:

        List<String> listA = new ArrayList<>(Arrays.asList("z","a", "b", "c"));
        List<String> listB = new ArrayList<>(Arrays.asList("e","a", "b", "z", "c", "d"));
        Set<String> setCombined = new HashSet<>(listA);
        setCombined.addAll(listB);
        System.out.println(setCombined);
        List<String> listCombined = new ArrayList<>(setCombined);
        System.out.println(listCombined);
    

    Here, both in setCombined and in listCombined you will have your items without duplicates and ordered, you can use any of the two to present the data according to your requirements.

    The output on the screen is this:

    [a, b, c, d, e, z]
    [a, b, c, d, e, z]
    

    Here, you can see a DEMONSTRATION IN REXTESTER

        
    answered by 16.08.2018 в 21:18
    0

    One way would be to convert array to List , concatenate them and delete repeated elements in listFinal , by this method:

    //elimina duplicados.
    List<String> listFinal = Stream.concat(list1.stream(), list2.stream())
                         .distinct()
                         .collect(Collectors.toList());
    

    The complete procedure would be:

    String[] listA = {"a","b","c"};
    String[] listB = {"e","a","b","d","c"};
    
    //Convierte a List ambos arreglos        
    List<String> list1 = new ArrayList<String>(Arrays.asList(listA));
    List<String> list2 = new ArrayList<String>(Arrays.asList(listB));
    
    //Concatena listas.       
    List<String> listFinal = Stream.concat(list1.stream(), list2.stream())
                         .distinct()
                         .collect(Collectors.toList());
    
    //Ordena lista
    Collections.sort(listFinal);        
    
    
    //al final obtienes una lista que no incluye elementos repetidos
    listFinal.forEach(System.out::println);
    

    Exit:

    a
    b
    c
    d
    e
    
        
    answered by 16.08.2018 в 19:53