- Given a HashSet containing String objects in java.
- HashSet will be containing Sport’s name.
- Convert HashSet <String> to ArrayList<String> in java.
- We will use the constructor of ArrayList to achieve the conversion.
Program – convert HashSet of Strings to ArrayList in java
package org.learn.collection.set.hset;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
public class DemoHashSetToArrayList {
public static void main(String[] args) {
Set<String> setSports = new HashSet<>();
setSports.add("Tennis");
setSports.add("Cricket");
setSports.add(null);
setSports.add("Basketball");
setSports.add("Cricket");
setSports.add(null);
setSports.add("Golf");
setSports.add("Boxer");
System.out.println("Set: "+ setSports);
ArrayList<String>hashSetToArrayList = new ArrayList<>(setSports);
System.out.println("ArrayList:"+ hashSetToArrayList);
}
}
Output – convert HashSet of String objects to ArrayList in java
Set: [null, Tennis, Cricket, Golf, Basketball, Boxer]
ArrayList:[null, Tennis, Cricket, Golf, Basketball, Boxer]