Java Problems with Solutions
Find Duration in Hours and Minutes Between Two Dates in Java
Sort a Java List Alphabetically First and then by Numbers
Encryption and Decryption of Strings in Java
Generate a Random String of Specific Length in Java
Split a String by Comma and Space in Java
Remove Duplicates from a Java List
Converting HashSet to List in Java
Calculate Days Between Two Dates in Java
Round a Number to N decimal Places in Java
Java Run Multiple Tasks Simultaneously
Filling Values in Editable PDF Forms in Java
Create ICS Calendar File in Java/Spring Boot
Convert LocalDateTime to Milliseconds in Java
Convert String DateTime To LocalDateTime in Java
Convert LocalDateTime to String in Java
Convert JSON Array to List of Long Type in Java
Convert a List to an Array in Java
Convert an Array to a List in Java
Convert POJO Class Object to JSON String in Java
Convert JSON String to POJO Class Object in Java
How to Add Data to a List in Java
How to avoid Deadlock in Java with Example
Counting Unique Numbers in a List of Integers
Extract Created and Modified Datetime of Files in Java
Remove Matching Items from List Ignoring Case
Java Solved Programs and Problems with Solutions
Java LocalDateTime Formatting
Merge Sets and Convert to List in Java
Working with CSV files in Java: Read and Write Data with Ease
Resolving Java Type Mismatch Error: Cannot Convert from List<int[]> to List<Integer>
Validating Email with Regex in Java
Converting HashSet to List in Java: Example and Explanation
- Last updated Apr 26, 2024
The code in this example provides a demonstration of converting a HashSet to a List in Java. The HashSet is a collection that does not allow duplicate elements and does not maintain any specific order. On the other hand, a List is an ordered collection that allows duplicate elements.
Example:
import java.util.ArrayList; import java.util.HashSet; import java.util.stream.Collectors; public class Example { public static void main(String[] args) { HashSetfruitHashSet = new HashSet<>(); fruitHashSet.add("mango"); fruitHashSet.add("apple"); fruitHashSet.add("orange"); fruitHashSet.add("papaya"); fruitHashSet.add("coconut"); // converting from hashset to list ArrayList fruitList = (ArrayList ) fruitHashSet.stream().collect(Collectors.toList()); // accessing items using for loop for (int i = 0; i < fruitList.size(); i++) { System.out.println(fruitList.get(i)); } } }
Output:
orange papaya apple mango coconut