Delete repeats of values in Arraylist

Asked

Viewed 2,461 times

2

I got 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());

He returns this:

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

But I want it to stay that way:

[2, 11, 12, 13, 14]

Because I want to either eliminate the repeaters or group the values.

2 answers

3


Utilize 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());
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Has a more "manual solution" that works in versions before Java 8. I don’t like these solutions HashSet, although internally it is likely that the distinct() to use, but at least it’s an implementation detail.

  • It worked! Thank you very much!

2

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

For example:

Set<Integer> semDuplicidade = new TreeSet<>(sequencia); // sua lista

Browser other questions tagged

You are not signed in. Login or sign up in order to post.