How to find unique values in array using java

We can find the unique values in an array using a HashSet in Java. Since a HashSet does not allow duplicate elements, adding all array values to a HashSet will automatically remove duplicates.

We have added values of array to set using for loop to obtain only the unique values.

Below is an example demonstrating this approach using Java with Selenium.

Example Code:

import java.util.Set;
import java.util.HashSet;
import java.util.Arrays;
import org.testng.annotations.Test;

public class ExceptionCheck {


@Test
public void findUniqueValues() {
    Integer[] arr = {3, 2, 3, 4, 2, 5};
    Set<Integer> uniqueValues = new HashSet<>();
         for(int val:arr) {
            uniqueValues.add(val);
	 }
    System.out.println(uniqueValues);
}

}

Watch YouTube Video here: How to find unique values of an array in java

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Subscribe to our YouTube Channel: Testing Talks Latest
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox
Scroll to Top
0
Would love your thoughts, please comment.x
()
x