WLA
WLA

Reputation: 15

Find Repeated Digits In List with Java

I am working on Pi Finder app.I know there is a lot of apps about it but i want to do it myself.I did it with Leibniz formula but it is working very slow because of repeated numbers.I am using lists for storage.Can you help me about find repeated numbers in lists or arrays?

Example {1,2,5,4,7,6,4,7,6,4,7,....} I need to find 4,7,6

Upvotes: 1

Views: 494

Answers (1)

Ousmane D.
Ousmane D.

Reputation: 56433

You can find the duplicate elements by using a Set as the accumlator and then utilise Collections.frequency to check if a given number occurs more than once within the List<Integer> like this:

List<Integer> elements = new ArrayList<>(Arrays.asList(1,2,5,4,7,6,4,7,6,4,7));
Set<Integer> accumulator = new LinkedHashSet<>(); 
for (Integer number : elements) {
   if(Collections.frequency(elements, number) > 1)
       accumulator.add(number);   
}

now the accumulator contains:

[4, 7, 6]

LinkedHashSet is utilised here to maintain insertion order. if that is not required then you can use a HashSet instead.

or a better performant solution as suggested by JB Nizet:

List<Integer> elements = new ArrayList<>(Arrays.asList(1,2,5,4,7,6,4,7,6,4,7));
Set<Integer> tempAccumulator = new LinkedHashSet<>();
Set<Integer> resultSet = new LinkedHashSet<>();
for (Integer number : elements) {
     if(!tempAccumulator.add(number))
        resultSet.add(number);
}

Upvotes: 1

Related Questions