Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,026 questions

51,982 answers

573 users

How to get all the unique elements of an array in Java

2 Answers

0 votes
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        int[] arr = {6, 7, 3, 3, 3, 5, 5, 7, 7, 1, 3};

        // Convert the array to a Set to get unique elements
        Set<Integer> uniqueSet = new HashSet<>();
        for (int num : arr) {
            uniqueSet.add(num);
        }

        // Convert the Set back to a List if needed, or print directly
        List<Integer> uniqueList = new ArrayList<>(uniqueSet);
        
        System.out.println(uniqueList);
    }
}

 
 
/*
run:
 
[1, 3, 5, 6, 7]
 
*/

 



answered Mar 28, 2025 by avibootz
0 votes
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Main {
    public static List<Integer> getUniqueElements(int[] arr) {
        // Create a HashSet to store unique elements
        Set<Integer> uniqueSet = new HashSet<>();
        for (int num : arr) {
            uniqueSet.add(num);
        }

        // Convert the Set to a List for the result
        return new ArrayList<>(uniqueSet);
    }

    public static void main(String[] args) {
        int[] arr = {6, 7, 3, 3, 3, 5, 5, 7, 7, 1, 3};
        
        List<Integer> uniqueElements = getUniqueElements(arr);

        System.out.println(uniqueElements);
    }
}

 
 
/*
run:
 
[1, 3, 5, 6, 7]
 
*/

 



answered Mar 28, 2025 by avibootz
...