Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


Ian Hawe
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;
        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.