Delete repeated components java

1

I am trying to add to a new list the components that are not repeated from the original list. I have made this code but it does not work. If someone can help me ...

public static <E> IndexedList<E> deleteRepeated(IndexedList<E> l)
{
  IndexedList<E> list = new ArrayIndexedList<E>();
     for(int i=0;i<=l.size();i++) 
     {
        for(int j=0;j<list.size();j++)
        {       
            if(list.get(i).equals(l.get(j)))
            {
                list.removeElementAt(i);
                j=0;
            }
        }
      }
         return list;
}
    
asked by susn 17.09.2018 в 19:27
source

3 answers

2

What you want to do is solved with a java.util.Set. The Set does not support repeated, which would not have to remove anything.

On the other hand if you want to keep using the list, you can do something like this:

private List<String> removeReated(List<String> originalValues) {
    List<String> newValues = new ArrayList<>();
    for (int i = 0; i < originalValues.size(); i++) {
        int repeated = 0;
        if (originalValues.contains(originalValues.get(i))) {
            repeated++;
            if (repeated < 1) {
                newValues.add(originalValues.get(i));
            }
        }
    }
    return newValues;
}

EDIT: The correct solution is to use a set:

Set mySet = new HashSet();
    
answered by 17.09.2018 в 20:08
0

Use a set and be sure to overwrite the equals method on the objects that you pass to the method.

In both cases you. Equals will not work if you do not overwrite the equals method because although the values are the same, your objects are different.

    
answered by 19.09.2018 в 11:02
0

The easiest thing is through streams :

private List<String> removeReated(List<String> originalValues) {
    return originalValues
        .stream()
        .distinct()
        .collect(Collectors.toList());
}
    
answered by 19.09.2018 в 11:44