Find length of non-repeated numbers in array How can I optimize this code which can get the length of non-repeated numbers in an array?
package com.sujay.practice;

import java.util.HashMap;
import java.util.Map;

/**
 * Find the length of non-repeated numbers in an array
 * @author Sujay
 * 08-May-2018
 */
public class DuplicateValuesInArray {

    public static void main(String[] args) {
        int[] array = { 1, 2, 2, 3, 4, 5, 6, 2, 4, 5, 3 };
        usingMap(array);
        usingString(array);
    }

    private static void usingString(int[] array) {
        String str = &quot;&quot;;
        for (int i = 0; i &lt; array.length; i++) {
            String temp = String.valueOf(array[i]);
            if (!str.contains(temp)) {
                str = str + temp;
            }
        }
        System.out.println(str.length());
    }

    private static void usingMap(int[] array) {
        Map&lt;Integer, Integer&gt; map = new HashMap&lt;Integer, Integer&gt;();
        for (int i = 0; i &lt; array.length; i++) {
            map.putIfAbsent(array[i], i);
        }
        System.out.println(map.size());
    }
}
The correct data structure to use to eliminate duplicates is a Set. The String processing is more expensive, and the Map code is less clear because you don't care at all about the values.
It's nice to provide a vararg parameter so that clients don't need to define an array if they don't want to.
It's a better practice to return your result from the method. If the client wants to print it, that's up to them. But if you print it, and the client changes what they want to do with it, they're out of luck.
You can used the enhanced for loop to make your code a little prettier.
More descriptive names are better than less descriptive names.


If I were to take a stab at writing your code with the above changes in mind, it might look something like:

private static int countUniqueValues(final int... values) {
    final Set&lt;Integer&gt; uniqueValues = new HashSet&lt;&gt;(values.length);
    for (final int value : values) {
        uniqueValues.add(value);
    }
    return uniqueValues.size();
}