Core java - Advance Topics
  • Welcome
  • Schedule
  • 1) Exception Handling
    • 1) Introduction to Exception Handling
    • 2) Categories of Exceptions
    • 3) Creating a method that throws an exception
    • 4) Creating Custom Exception Classes
    • 5)What happens when an exception is thrown?
      • 5.1) Creating try-catch-finally blocks
      • 5.2) Using a method that throws a checked exception
      • 5.3) Using a method that throws a runtime exception
      • 5.4) Using a method that throws an error
      • 5.5) Will a finally block execute even if the catch block defines a return statement?
      • 5.6) What happens if both a catch and a finally block define return statement?
      • 5.7) What happens if a finally block modifies the value returned from a catch block?
      • 5.8) Can a try block be followed only by a finally block?
      • 5.9) Does the order of the exceptions caught in the catch blocks matter?
      • 5.10) Can I rethrow an exception or the error I catch?
      • 5.11) Can I declare my methods to throw a checked exception instead of handling it?
      • 5.12) I can create nested loops, so can I create nested try-catch blocks too?
      • 5.13) Should I handle errors?
    • 6) Best Practices
    • 7) Cheat Sheet
    • 8) Problems
  • 2) Wrapper Classes and Enums
    • 2.1) Creating objects of the wrapper classes
    • Enums
  • 3) Inner Classes
    • 3.1) Static nested class (also called static inner class)
    • 3.2) Inner class (also called member class)
    • 3.3) Anonymous inner class
    • 3.4) Method local inner classes
    • CheatSheet
  • 4) Generics
    • Multiple Type parameters in Generic classes
    • Inheritance using Generics
    • Generic interfaces
    • Generic Methods
    • Bounded type parameters
    • Applications
  • 5) Equals and Hashcode
    • Problems
  • CompareTo method overview
  • Basic DS
    • 1) Simple Array List
    • 2) Simple HashMap
  • 5) Collections Framework - Part 1
    • Introducing the collections framework
    • Working with the Collection interface
      • The core Collection interface
      • Methods of the Collection interface
    • Creating and using List, Set, and Deque implementations
      • List interface and its implementations
      • Iterators
      • Sorting List using custom sorting technique
      • Comparable Interface
      • Custom Sorting using comparator
      • ArrayList - Examples and practice problems
    • Stack
    • Linked List
    • LinkedList Operations
  • 6) Collections Framework - Part 2
    • Sets
      • Set Types
      • Array to Set (vice versa)
    • Maps
    • TreeMap
    • Autoboxing And Unboxing
  • Collections Framework - Part 3
    • Basics : DS , Number System
    • Internal Working
      • HashMap
      • HashSet
  • 7) Reflection API
  • 8) Annotations
  • 9) Reading Input From Various Sources
    • File Handling
    • Reading From Xml
    • Reading From JSON
  • 10) Multi-threading (Concurrency)
    • Protect shared data
    • Thread-safe access to shared data
  • 11) Design Patterns
    • Singleton
    • DI
  • 12) Internal Working of JVM
  • 13) Garbage Collection
  • 14) More on Strings (Buffer and Builder)
  • 15) Cloning and Immutable Class
    • 16) Serialization And Deserialization
    • Untitled
  • JAVA 8
    • Interface Changes
    • Lambda
    • Method Ref
    • Optional
    • Streams
    • Predicates
  • Practice Tests
    • Test - Collections
    • OOPS
    • S-OOPS
Powered by GitBook
On this page
  • Java Array to Set
  • Java Set to Array
  • Example :

Was this helpful?

  1. 6) Collections Framework - Part 2
  2. Sets

Array to Set (vice versa)

Java Array to Set

Unlike List, We cannot convert a Java Set into an array directly as it’s NOT implemented using an Array. So We cannot use Arrays class to get the view of array as set. We can follow another approach. We can convert an array into List using Arrays.asList() method, then use it to create a Set. By using this approach, we can covert a Java Array to Set in two ways. Let us discuss them one by one using one simple example.

Approach-1 In this approach, first We need to create a List using given array and use it to create a Set as shown below.

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class ArrayToSet {
	public static void main(String[] args) {

		String[] vowels = { "a", "e", "i", "o", "u" ,"e"};

		Set<String> vowelsSet = new HashSet<String>(Arrays.asList(vowels));
		System.out.println(vowelsSet);

		/**
		 * Unlike List, Set is NOt backed by array, so we can do structural modification
		 * without any issues.
		 */
		vowelsSet.remove("e");
		System.out.println(vowelsSet);
		vowelsSet.clear();
		System.out.println(vowelsSet);
	}
}
[a, e, u, i, o]
[a, u, i, o]
[]

Approach-2 In this approach, we do NOT use intermediate List to create a Set from an Array. First create an empty HashSet, then use Collections.addAll() to copy array elements into the given Set as shown below.

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class ArrayToSet2 {
	public static void main(String[] args) {

		String[] vowels = { "a", "e", "i", "o", "u" };

		Set<String> vowelsSet = new HashSet<>();

		Collections.addAll(vowelsSet, vowels);

		System.out.println(vowelsSet);

		/**
		 * Unlike List, Set is NOt backed by array, so we can do structural modification
		 * without any issues.
		 */
		vowelsSet.remove("e");
		System.out.println(vowelsSet);
		vowelsSet.clear();
		System.out.println(vowelsSet);
	}
}
[a, e, u, i, o]
[a, u, i, o]
[]

Java Set to Array

In this section, we will write a program to convert a Set of Strings into an Array of String using Set.toArray() method as shown below.

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class SetToArray {
	public static void main(String[] args) {
		Set<String> vowelsSet = new HashSet<String>();

		// add example
		vowelsSet.add("a");
		vowelsSet.add("e");
		vowelsSet.add("i");
		vowelsSet.add("o");
		vowelsSet.add("u");

		// convert Set to Array
		String strArray[] = vowelsSet.toArray(new String[vowelsSet.size()]);
		System.out.println(Arrays.toString(strArray));
	}
}
[a, e, u, i, o]

Example :

package certification.collections;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class SetFromArray {
	public static void main(String[] args) {

		// Converting list to set
		List<Integer> integers = new ArrayList<>();
		integers.add(2);
		integers.add(2);
		integers.add(3);
		integers.add(4);

		Set<Integer> integers2 = new HashSet<>(integers);
		System.out.println(integers2);

		// Array to list
		Integer[] array = { 2, 3, 45, 4, 2, 4, 5, 2 };

		List<Integer> integers3 = Arrays.asList(array);

		Set<Integer> integers4 = new HashSet<>(integers3);

		System.out.println(integers4);

		// set to array
		Object[] array2 = integers4.toArray();

		for (Object integer : array2) {
			System.out.println(integer);
		}
	}
}
[2, 3, 4]
[2, 3, 4, 5, 45]
2
3
4
5
45
PreviousSet TypesNextMaps

Last updated 6 years ago

Was this helpful?