Java set to list string

Convert Set to List in Java and Vice-versa

In Java, List and Set are Collections types to store elements. List is an index-based ordered collection, and Set is an unordered collection. List allows duplicate elements, but Set contains only unique elements. Both collection types are quite different and have their own usecases.

In this Java tutorial, Learn to convert a specified Set to a List. Also, learn to reverse convert List to Set, a useful method to remove duplicate elements from a list.

We will be using the following Set to List type in different ways.

1.1. Using List Constructor

To convert a given Set to a List, we can use the ArrayList constructor and pass HashSet as the constructor argument. It will copy all elements from HashSet to the newly created ArrayList.

ArrayList arrayList = new ArrayList(set); Assertions.assertEquals(3, arrayList.size());

Another useful method to get a List with Set elements is to create an empty list instance and use its addAll() method to add all the elements of the Set to List.

ArrayList arrayList = new ArrayList<>(); arrayList.addAll(set); Assertions.assertEquals(3, arrayList.size());

First, convert the Set to Stream, and then collect the Stream elements to List.

List list = set.stream().toList(); Assertions.assertEquals(3, list.size());

We might need to create a HashSet from a specified ArrayList when we want to remove duplicates from the list because sets do not allow duplicate items.

Читайте также:  Public abstract int java

Let us begin with creating a List instance, and then we will convert it to the Set. The list contains 7 items, but only 4 unique items. So the Set size must be 4 in each method.

List list = List.of(1, 2, 3, 3, 3, 5, 5);

Similar to the previous example, we can use the constructor HashSet(collection) to convert to initialize a HashSet with the items from the ArrayList.

Set set = new HashSet(list); Assertions.assertEquals(4, set.size());

The Set.addAll(list) adds all of the elements in the specified collection to this set if they’re not already present.

Set set = new HashSet(); set.addAll(list); Assertions.assertEquals(4, set.size());

Similar to the previous section, we can convert a set to list using the Stream as follows:

Set set = list.stream().collect(Collectors.toSet()); Assertions.assertEquals(4, set.size());

Источник

How to Convert Set to List in Java

How to Convert Set to List in Java

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Lists in Java are ordered collection of data, whereas sets are an unordered collection of data. A list can have duplicate entries, a set can not. Both the data structures are useful in different scenarios. Knowing how to convert a set into a list is useful. It can convert unordered data into ordered data.

Initializing a set

import java.util.*; public class Main  public static void main(String[] args)  SetInteger> a = new HashSet>(); a.add(1); a.add(2); a.add(3); a.add(1); System.out.println(a); > > 

Set

The add() method of HashSet adds the elements to the set. Note that the elements are distinct. There is no way to get the elements according to their insertion order as the sets are unordered.

Converting Set to List in Java

Let’s convert the set into a list. There are multiple ways of doing so. Each way is different from the other and these differences are subtle.

1. List Constructor with Set argument

The most straightforward way to convert a set to a list is by passing the set as an argument while creating the list. This calls the constructor and from there onwards the constructor takes care of the rest.

import java.util.*; public class Main  public static void main(String[] args)  SetInteger> a = new HashSet>(); a.add(1); a.add(2); a.add(3); a.add(1); ListInteger> arr = new ArrayList>(a); System.out.println(arr); System.out.println(arr.get(1)); > > 

Using Constructor

Since the set has been converted to a list, the elements are now ordered. That means we can use the get() method to access elements by index.

2. Using conventional for loop

We can use the good old for loop to explicitly copy the elements from the set to the list.

import java.util.*; public class Main  public static void main(String[] args)  SetInteger> a = new HashSet>(); a.add(1); a.add(2); a.add(3); a.add(1); ListInteger> arr = new ArrayList>(a); for (int i : a) arr.add(i); System.out.println(arr); System.out.println(arr.get(1)); > > 

Using for-loop

For loop goes over the set element by element and adds the elements to the list.

3. List addAll() method

Lists have a method called addAll() that adds multiple values to the list at once. You might recall this operation from its use in merging two lists. addAll() also works for adding the elements of a set to a list.

import java.util.*; public class Main  public static void main(String[] args)  SetInteger> a = new HashSet>(); a.add(1); a.add(2); a.add(3); a.add(1); ListInteger> arr = new ArrayList>(); arr.addAll(a); System.out.println(arr); System.out.println(arr.get(1)); > > 

Using addAll()

4. Stream API collect() method

Stream.collect() is available from Java 8 onwards. ToList collector collects all Stream elements into a List instance.

import java.util.*; import java.util.stream.Collectors; public class Main  public static void main(String[] args)  SetInteger> a = new HashSet>(); a.add(1); a.add(2); a.add(3); a.add(1); ListInteger> arr; arr = a.stream().collect(Collectors.toList()); System.out.println(arr); System.out.println(arr.get(1)); > > 

using stream.collect()

The documentation for stream.collect() mentions that there is no guarantee on the type, mutability, serializability, or thread-safety of the List returned. If more control over the returned List is required, use toCollection(Supplier). To specify the type of list use toCollection(ArrayList::new)

import java.util.*; import java.util.stream.Collectors; public class Main  public static void main(String[] args)  SetInteger> a = new HashSet>(); a.add(1); a.add(2); a.add(3); a.add(1); ListInteger> arr; arr = a.stream().collect(Collectors.toCollection(ArrayList::new)); System.out.println(arr); System.out.println(arr.get(1)); > > 

5. List.copyOf() method

Java 10 onwards List has a copyOf() method. The method returns an unmodifiable List containing the elements of the given Collection, in its iteration order. The list can’t contain any null elements. In case the set contains ‘null’, the method returns a null pointer exception.

import java.util.*; import java.util.stream.Collectors; public class Main  public static void main(String[] args)  SetInteger> a = new HashSet>(); a.add(1); a.add(2); a.add(3); a.add(1); ListInteger> arr; arr = List.copyOf(a); System.out.println(arr); System.out.println(arr.get(1)); > > 

using List.copyOf()

Adding a null in the set and trying to convert to a list :

import java.util.*; import java.util.stream.Collectors; public class Main  public static void main(String[] args)  SetInteger> a = new HashSet>(); a.add(1); a.add(2); a.add(3); a.add(1); a.add(null); ListInteger> arr; arr = List.copyOf(a); System.out.println(arr); System.out.println(arr.get(1)); > > 

Null Pointer ExceptionIf you try to add an element to an immutable list you’ll get an error that looks like the following. Immutable ErrorUsing the addAll() method to convert set with null element to a list :

import java.util.*; import java.util.stream.Collectors; public class Main  public static void main(String[] args)  SetInteger> a = new HashSet>(); a.add(1); a.add(2); a.add(3); a.add(1); a.add(null); ListInteger> arr = new ArrayList>(); arr.addAll(a); // arr = List.copyOf(a); System.out.println(arr); System.out.println(arr.get(1)); > > 

AddAll() with Null

Note that the null appears at the beginning of the list.

Conclusion

We saw some really interesting methods to convert a set into a list. It’s important to pay attention to the type of list that is created from each method. Like copyOf() method produces an immutable list and can’t handle null elements. Whereas, stream.collect() doesn’t guarantee anything. Constructor and addAll() are the most trustworthy among the batch.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us

Источник

How to convert a set to a list in Java

Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.

A Java set is a part of the java.util package; it extends the java.util.Collection interface. A Java set does not allow any duplicate item and allows only one null element.

A Java list is an ordered collection of items. Unlike a Java Set, a Java list can accommodate duplicate values.

Conversion

There are two methods used to convert a set to a list:

  1. Adding all the elements of the set to the list individually.​
  2. Using the constructor of the list and passing the set to it.

Implementation of the first method

import java.util.*;
import java.util.stream.*;
class example
// Generic function to convert set to list
public static List convertSetToList(Set set)
// create an empty list
List list = new ArrayList<>();
// push each element in the set into the list
for (T t : set)
list.add(t);
// return the list
return list;
>
public static void main(String args[])
// Create a Set using HashSet
Set hash_Set = new HashSet();
// Add elements to set
hash_Set.add("Educative's");
hash_Set.add("example");
hash_Set.add("Set");
hash_Set.add("to");
hash_Set.add("list");
// Print the Set
System.out.println("Set: " + hash_Set);
// construct a new List from Set
List list = convertSetToList(hash_Set);
// Print the List
System.out.println("List: " + list);
>
>

Implementation of the second method

import java.util.*;
import java.util.stream.*;
class example
// Generic function to convert set to list
public static List convertSetToList(Set set)
// create a list from Set
List list = new ArrayList<>(set);
// return the list
return list;
>
public static void main(String args[])
// Create a Set using HashSet
Set hash_Set = new HashSet();
// Add elements to set
hash_Set.add("Educative's");
hash_Set.add("example");
hash_Set.add("Set");
hash_Set.add("to");
hash_Set.add("list");
// Print the Set
System.out.println("Set: " + hash_Set);
// construct a new List from Set
List list = convertSetToList(hash_Set);
// Print the List
System.out.println("List: " + list);
>
>

Learn in-demand tech skills in half the time

Источник

Java set to list string

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Оцените статью