Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Ian Hawe
PLUS
Ian Hawe
Courses Plus Student 10,579 Points

Comparing an array to itself to get distinct values using Java

public static void main(String[] args) { int[] data = {81, 81, 4, 1, 1, 2, 3, 81, 4, 5, 6, 7, 8, 9, 10, 10, 12, 1, 81}; findDistinctElements(data); }

public static void findDistinctElements(int[] data) {
    for (int i = 0; i < data.length; i++) {
        boolean distinct = true;
        for (int j = 0; j < i; j++) {
            if (data[i] == data[j]) {
                distinct = false;
                break;
            }
        }
        if (distinct) {
            System.out.print(data[i] + " ");
            //81,4,1,2,3,5,6,7,8,9,10,12 = Distinct numbers
        }
    }
}

Are there any other methods to do this? or more easier to read methods? perhaps performance increasing?

1 Answer

Manish Giri
Manish Giri
16,266 Points

You can create a HashSet from the array, which will contain only the distinct values in the array.