How to store unique values in Java using Set?

Ads
 
Tutorials   
How to replace all occurrences of a string in JavaScript? How to convert a stack trace to a string? Example code of reading file line by line in Java with Apache Commons IO library How to store unique values in Java using Set? java.nio ShortBuffer Example How to use Java Path class? Java NIO Package Tutorial How to limit object creation in Java? Java 11 String lines function example to split it in lines Top upcoming features of JDK 11 Java/JDK 11 Tutorial How to install JDK 10 in Ubuntu 18.04? Install JDK 10 on Windows Java 10 features Processing large file in Java Learning Java for non programmers Why You Should Learn Java in 2018? Installing JDK 9 on Windows 10 How to convert binary to decimal in Java? How to add two numbers in Java? What is Applet in Java with Example? What is nested class in Java with Example? Exception handling in Java Programming Examples What is Constructor Overloading in Java? How to display image in Swing? What is Java programming used for? How to create custom exception in Java? How to set CLASSPATH in Java? What is Multithreading in Java? IO Streams in Java with Examples How to convert String Date to Timestamp in Java? Best Java Tutorial for Beginners Read user input in Java using Scanner Java Programming Examples Read file line by line in Java 8 What are the benefits of learning Java Programming? A brief history and future of Java programming language Importance of Java for Mobile Application Development How To Become A Good Software Developer? Learn Java Programming for beginners

How to store unique values in Java using Set?

In this tutorial we are going to use Set in Java for storing unique values. Set interface in Java can be used to store unique values within you program.

In this tutorial we are going to use Set in Java for storing unique values. Set interface in Java can be used to store unique values within you program.

Store unique values in Java using Set interface

In this section we will discuss about the Set interface in Java which is designed to store unique values. We will show you how to store unique values in Java using Set? The Set interface in Java allows allows maintaining unique list in Java. Here in this example we will use HashSet to maintain list of of unique values in our program. First of all we will initialize the HashSet object and then add few values including duplicates. When we add duplicates the Set interface checks if the elements already exists if it does not already presents then it adds in the list. If value is already present then it skips and value is not added to the list. This way it maintains the unique values list in Java.

Introduction to HashSet in Java

As explained earlier Set interface in Java is used to store the unique values and HashSet is one of the most popular implementation of this interface. The HashSet is part of core Java API and it provides many methods to perform operation on the values stored in the HashSet object.

HashSet is one of the fundamental data structure in Java and its main features are:

  • It is used to store unique elements
  • It also permits null
  • The HashSet is backed by HashMap
  • The HashSet does not maintain the insertion order
  • Its not thread safe so in multithreading environment it should be used carefully

Methods of HashSet

HashSet provides following important methods to perform various operations on the HashSet object:

  • The add() method - This method is used to add an object to the HashSet object. If duplicate value is sent in the add method, it simply ignores the value.
     
  • The contains() method  - This method is used to find if HashSet object contains the specified value. It returns true if value is present or false if value is already not present in the Set object.
     
  • The remove() method - This method is used to removed a value from the HashSet object. It returns true if values was present and removed.
     
  • The clear() method - This method is used to clear the object data.
     
  • The size() method - This method is used to find out the count of values stores in the HashSet object.
     
  • The isEmpty() - This method is used to find if the object is empty.

We have seen some of the important methods of HashSet object. Now lets write simple program to store unique values in the HashSet object and then print the data. We are going to store same values two times and then print the data. When we iterate and print the data it only prints the unique values.

Here is the example program to store unique values in Java using HashSet:

package net.roseindia;
// Web: https://www.roseindia.net
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class UniqueValues {

	public static void main(String[] args) {
		Set set = new HashSet();
		set.add("One");
		set.add("Two");
		set.add("Three");

		set.add("One");
		set.add("Two");
		set.add("Three");
				
		Iterator itr = set.iterator();
		while(itr.hasNext()){
			String value = itr.next();
			System.out.println(value);
		}

	}

}

In the above tutorial we are instantiating the object of HashSet:

Set set = new HashSet();

Then adding following values two times:

set.add("One");
set.add("Two");
set.add("Three");

Then printing the values stored in the HashSet object with the help of following code:

Iterator itr = set.iterator();
while(itr.hasNext()){
	String value = itr.next();
	System.out.println(value);
}

Following is the output of the program:

One
Two
Three

From the above output of the program it is clear that the HashSet is stores unique values. If duplicate value is added multiple times, then it just ignores.

In this tutorial you have learned to store unique values in Java using the HashSet object. Keep in mind that the HashSet is not thread safe and you should use it with care in multi-threading environment.

Here are more tutorials related to HashSet:

Ads

Ads