Java Coding Program

Share

 I’ll provide you with an example of a Java program that finds unique elements in an array. In this program, we will remove any duplicate elements from the array and return a new array containing only the unique elements.

Here’s the Java code:

java

Copy code

import java.util.ArrayList;

import java.util.HashSet;

public class UniqueElements {

    public static int[] findUniqueElements(int[] arr) {

        HashSet<Integer> uniqueSet = new HashSet<>();

        ArrayList<Integer> uniqueList = new ArrayList<>();

        for (int num : arr) {

            if (!uniqueSet.contains(num)) {

                uniqueSet.add(num);

                uniqueList.add(num);

            }

        }

        int[] uniqueArray = new int[uniqueList.size()];

        for (int i = 0; i < uniqueArray.length; i++) {

            uniqueArray[i] = uniqueList.get(i);

        }

        return uniqueArray;

    }

    public static void main(String[] args) {

        int[] inputArray = {1, 2, 2, 3, 4, 4, 5, 5, 6};

        int[] uniqueElements = findUniqueElements(inputArray);

        System.out.print(“Original Array: “);

        for (int num : inputArray) {

            System.out.print(num + ” “);

        }

        System.out.print(“\nUnique Elements: “);

        for (int num : uniqueElements) {

            System.out.print(num + ” “);

        }

    }

}

This program defines a method findUniqueElements, which takes an integer array as input and returns an array containing only the unique elements from the input array. The HashSet is used to keep track of unique elements encountered, and the ArrayList is used to store the unique elements in the order they appear.

The main method demonstrates how to use this findUniqueElements method with a sample input array. The output will display the original array and the unique elements separately.

Feel free to modify the inputArray in the main method to test the program with different sets of numbers.

Demo Day 1 Video:

 
You can find more information about Java in this Java Docs Link

 

Conclusion:

Unogeeks is the No.1 Training Institute for Java Training. Anyone Disagree? Please drop in a comment

You can check out our other latest blogs on Java Training here – Java Blogs

You can check out our Best in Class Java Training details here – Java Training

💬 Follow & Connect with us:

———————————-

For Training inquiries:

Call/Whatsapp: +91 73960 33555

Mail us at: info@unogeeks.com

Our Website ➜ https://unogeeks.com

Follow us:

Instagram: https://www.instagram.com/unogeeks

Facebook: https://www.facebook.com/UnogeeksSoftwareTrainingInstitute

Twitter: https://twitter.com/unogeeks


Share

Leave a Reply

Your email address will not be published. Required fields are marked *