Converting HashSet to List/ArrayList in Java
In Java, a List is an interface for holding an ordered collection of elements. Unlike a Set, a List allows duplicate elements, and it maintains the order of insertion.
In Java, a HashSet is a collection class that implements the Set interface. It represents a collection of unique elements, meaning it cannot contain any duplicate elements. HashSet is implemented using a hash table data structure, which makes it very efficient for lookups and insertions.
HashSets are unordered, meaning the elements are not stored in any specific order. Additionally, HashSet allows null values to be stored, but only one null value can be stored in a HashSet at a time.
HashSet may not be the best choice for scenarios where the order of elements is important as it does not maintain the order of insertion.
Here's an example for converting a HashSet of String elements to a List in Java:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.stream.Collectors;
public class Example {
public static void main(String[] args) {
HashSet<String> fruitHashSet = new HashSet<>();
fruitHashSet.add("mango");
fruitHashSet.add("apple");
fruitHashSet.add("orange");
fruitHashSet.add("papaya");
fruitHashSet.add("coconut");
// converting from hashset to list
ArrayList<String> fruitList = (ArrayList<String>) fruitHashSet.stream().collect(Collectors.toList());
// accessing items using for loop
for (int i = 0; i < fruitList.size(); i++) {
System.out.println(fruitList.get(i));
}
}
}
Here's another example for converting the HashMap values of a Map to a List in Java:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Test {
public static void main(String[] args) {
HashSet<String> fruits = new HashSet<>();
fruits.add("Grapes");
fruits.add("Mango");
fruits.add("Apple");
fruits.add("Papaya");
fruits.add("Pineapple");
HashSet<String> flowers = new HashSet<>();
flowers.add("Tulip");
flowers.add("Rose");
flowers.add("Sunflower");
flowers.add("Marigold");
Map<String, Object> map = new HashMap<>();
map.put("fruits", fruits);
map.put("flowers", flowers);
Set<String> newSet = new HashSet<>();
map.values().forEach(m->{
newSet.addAll((Set)m);
});
List<String> list = new ArrayList<>(newSet);
System.out.println(list);
}
}