Java Set How To Get Element
Java Set is a collection of elements (Or objects) that contains no duplicate elements. Coffee Set is an interface that extends Collection interface. Unlike List, Java Prepare is NOT an ordered collection, information technology'due south elements does NOT have a particular order. Java Prepare does Non provide a command over the position where you can insert an element. Yous cannot admission elements past their index and also search elements in the list.
Coffee Set
In this section, we will talk over some of the of import points about Java Set:
- Coffee Set interface is a member of the Java Collections Framework.
- Unlike Listing, Set DOES Not allow you lot to add duplicate elements.
- Gear up allows you to add at well-nigh one nix element only.
- Set interface got one default method in Java 8: spliterator.
- Different List and arrays, Set does NOT support indexes or positions of information technology'south elements.
- Prepare supports Generics and nosotros should utilize it whenever possible. Using Generics with Set will avert ClassCastException at runtime.
- We tin use Gear up interface implementations to maintain unique elements.
Java Fix Class Diagram
Java Prepare interface extends Drove interface. Collection interface extends Iterable interface. Some of the frequently used Set implementation classes are HashSet, LinkedHashSet, TreeSet, CopyOnWriteArraySet and ConcurrentSkipListSet. AbstractSet provides a skeletal implementation of the Set interface to reduce the effort in implementing Set.
Coffee Set Methods
In this section we volition discuss some of the useful Coffee Set methods:
- int size(): to get the number of elements in the Set.
- boolean isEmpty(): to cheque if Set is empty or not.
- boolean contains(Object o): Returns true if this Fix contains the specified chemical element.
- Iterator iterator(): Returns an iterator over the elements in this set. The elements are returned in no detail gild.
- Object[] toArray(): Returns an array containing all of the elements in this set. If this set makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order.
- boolean add(E due east): Adds the specified chemical element to this set if information technology is non already present (optional operation).
- boolean remove(Object o): Removes the specified element from this set if it is present (optional operation).
- boolean removeAll(Collection c): Removes from this prepare all of its elements that are contained in the specified collection (optional performance).
- boolean retainAll(Collection c): Retains simply the elements in this set that are contained in the specified collection (optional operation).
- void clear(): Removes all the elements from the set.
- Iterator iterator(): Returns an iterator over the elements in this set.
Java Array to Set
Unlike List, Nosotros cannot convert a Java Gear up into an array directly as it's NOT implemented using an Assortment.
So We cannot employ Arrays class to get the view of array as set. We can follow some other arroyo. Nosotros can convert an array into List using Arrays.asList() method, then utilise it to create a Set. Past using this approach, we can covert a Coffee Array to Set in two means. Let u.s. discuss them ane by one using i simple example.
Arroyo-i
In this arroyo, first We need to create a List using given array and use it to create a Set up as shown beneath.
import coffee.util.*; public class ArrayToSet { public static void chief(Cord[] args) { String[] vowels = {"a","e","i","o","u"}; Fix<String> vowelsSet = new HashSet>(Arrays.asList(vowels)); Organization.out.println(vowelsSet); /** * Dissimilar List, Set is NOt backed by array, * so we can do structural modification without any issues. */ vowelsSet.remove("e"); Organization.out.println(vowelsSet); vowelsSet.clear(); System.out.println(vowelsSet); } } Approach-2
In this approach, nosotros do NOT use intermediate List to create a Gear up from an Array. Outset create an empty HashSet, then apply Collections.addAll() to copy array elements into the given Prepare equally shown beneath.
import coffee.util.*; public class ArrayToSet2 { public static void main(String[] args) { String[] vowels = {"a","e","i","o","u"}; Fix<String> vowelsSet = new HashSet<>(); Collections.addAll(vowelsSet, vowels); System.out.println(vowelsSet); /** * Unlike List, Prepare is Non backed by array, * and so we can do structural modification without any issues. */ vowelsSet.remove("e"); System.out.println(vowelsSet); vowelsSet.clear(); System.out.println(vowelsSet); } } Output:-
When we run above two programs, we will get the same output equally shown below.
[a, due east, u, i, o] [a, u, i, o] [] Coffee Prepare to Assortment
In this section, nosotros will write a programme to convert a Set up of Strings into an Assortment of String using Fix.toArray() method equally shown below.
import java.util.*; public class SetToArray { public static void primary(String[] args) { Prepare<String< vowelsSet = new HashSet<>(); // add example vowelsSet.add("a"); vowelsSet.add together("due east"); vowelsSet.add("i"); vowelsSet.add("o"); vowelsSet.add("u"); //convert Set to Array Cord strArray[] = vowelsSet.toArray(new String[vowelsSet.size()]); Organisation.out.println(Arrays.toString(strArray)); } } Output:-
When we run in a higher place program, we will become the following output every bit shown below.
[a, east, u, i, o] Java Set Sorting
Every bit we know, Set up (HashSet) does NOT support sorting elements directly. It stores and display information technology'southward elements in random order.
Nonetheless, we have some approaches to sort it'south elements as shown below:
import java.util.*; public grade SetSortingExample { public static void primary(Cord[] args) { Fix<Integer> intsSet = new HashSet<>(); Random random = new Random(); for (int i = 0; i {render (o2-o1);}); System.out.println("Reverse Sorting: " + intsList2); // Arroyo-3 Set up<Integer> sortedSet = new TreeSet<>(intsSet); System.out.println("Sorted Set: " + sortedSet); } } Output:-
When we run above plan, we volition see the following output.
[560, 864, 176, 657, 135, 103, xl, 123, 555, 589] Natural Sorting: [40, 103, 123, 135, 176, 555, 560, 589, 657, 864] Before Sorting: [560, 864, 176, 657, 135, 103, twoscore, 123, 555, 589] Reverse Sorting: [864, 657, 589, 560, 555, 176, 135, 123, 103, forty] Sorted Set: [40, 103, 123, 135, 176, 555, 560, 589, 657, 864] Coffee Set up Common Operations
Most common operations performed on Coffee Set are add, addAll, clear, size etc. Below is a uncomplicated Coffee Set example showing common method usage.
import java.util.*; public class SetCommonOperations { public static void principal(String args[]) { Set<String> vowels= new HashSet<>(); //add example vowels.add("A"); vowels.add("Due east"); vowels.add together("I"); //We cannot insert elements based on alphabetize to a Fix System.out.println(vowels); Prepare<String> fix = new HashSet<>(); ready.add("O"); set.add("U"); //appending set elements to messages vowels.addAll(set); System.out.println(vowels); //articulate example to empty the set ready.clear(); //size example System.out.println("messages set size = " + vowels.size()); vowels.clear(); vowels.add("E"); vowels.add("Eastward");vowels.add("I"); vowels.add together("O"); System.out.println("Given set contains E element or not? = " + vowels.contains("E")); } } Output:-
[A, E, I] [A, E, U, I, O] letters fix size = five Given set contains Eastward element or not? = truthful Java Set Iterator
Below is a elementary example showing how to iterate over Java Set.
import java.util.*; public course SetIteratorExample { public static void master(Cord[] args) { Fix<Integer> set up = new HashSet<>(); for(int i=0; i<5; i++) set.add(i); Iterator iterator = set.iterator(); //uncomplicated iteration while(iterator.hasNext()){ int i = (int) iterator.side by side(); System.out.print(i + ", "); } Organization.out.println("\n" + gear up); //modification of prepare using iterator iterator = gear up.iterator(); while(iterator.hasNext()){ int 10 = (int) iterator.next(); if(ten%ii ==0) iterator.remove(); } System.out.println(set); //changing set structure while iterating iterator = set.iterator(); while(iterator.hasNext()){ //ConcurrentModificationException here int x = (int) iterator.next(); if(x==1) set up.add(10); } } } Coffee Prepare to Stream
Beneath is a unproblematic example showing how to convert a Java Set to Stream and perform some operations as per our requirements.
import java.util.*; public class SetToStream { public static void main(Cord[] args) { Gear up<String> vowelsSet = new HashSet<>(); // add together example vowelsSet.add("a"); vowelsSet.add("e"); vowelsSet.add("i"); vowelsSet.add("o"); vowelsSet.add("u"); //convert set to stream vowelsSet.stream().forEach(System.out::println); } } Output:-
a e u i o Coffee SE 9 Set
In Java SE 9 release, Oracle Corp is going to add some useful utility methods to Ready interface. Information technology's improve to understand them with some uncomplicated and useful examples.
Please get through my tutorial at "Java SE 9: Set Factory Methods" to acquire them.
That'south all of a quick roundup on Set in Java. I hope these Java Set examples volition assistance yous in getting started with Gear up collection programming.
Thank you for reading my tutorials. Please drop me a comment if yous like my tutorials or accept any bug or suggestions or any type errors.
Java Set How To Get Element,
Source: https://www.journaldev.com/13242/java-set
Posted by: taylorwituessarks43.blogspot.com

0 Response to "Java Set How To Get Element"
Post a Comment