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

Related questions

...