Delete duplicates of values in ArrayList [duplicate]

2

I have the following ArrayList<Integer> :

ArrayList<Integer> sequencia = new ArrayList<>();
sequencia.add(2);
sequencia.add(11);
sequencia.add(12);
sequencia.add(13);
sequencia.add(14);
sequencia.add(14);
System.out.println(sequencia.toString());

It returns this:

[2, 11, 12, 13, 14, 14]

But I want it to look like this:

[2, 11, 12, 13, 14]

I want to either delete the repeated ones or group the values.

    
asked by anonymous 27.12.2017 / 17:55

2 answers

2

Use streams to filter :

import java.util.*;
import java.util.stream.Collectors;

public class Program {
    public static void main (String[] args) {
        ArrayList<Integer> sequencia = new ArrayList<>();
        sequencia.add(2);
        sequencia.add(11);
        sequencia.add(12);
        sequencia.add(13);
        sequencia.add(14);
        sequencia.add(14);
        System.out.println(sequencia.stream().distinct().collect(Collectors.toList()).toString());
    }
}

See running on ideone . And in Coding Ground . Also I put it in GitHub for future reference .

You have a more "manual" solution that works on versions before Java 8. I do not like these HashSet , although internally it is likely that distinct() will use it, but at least it's an implementation detail.

    
27.12.2017 / 18:05
2

The simplest way is to use an implementation of the Set interface. More precisely a java.util.TreeSet .

For example:

Set<Integer> semDuplicidade = new TreeSet<>(sequencia); // sua lista
    
27.12.2017 / 18:00