To convert a comma-separated string to a HashSet in Java, you can follow these steps:
split()
method of the String class.add()
method of the HashSet class.Here's an example code snippet that demonstrates this process:
String csv = "apple,banana,orange"; String[] items = csv.split(","); Set set = new HashSet<>(); for (String item : items) { set.add(item); }
In this example, the csv
variable contains the comma-separated string, which is split into an array of strings using the split()
method. Then, a new HashSet is created to store the elements, and each element from the array is added to the HashSet using the add()
method.
Note that if the comma-separated string contains whitespace between the commas and the elements, you may want to trim the elements using the trim()
method to remove any leading or trailing whitespace:
String csv = "apple, banana, orange "; String[] items = csv.split(","); Set set = new HashSet<>(); for (String item : items) { set.add(item.trim()); }
Here, the trim()
method is called on each element to remove any leading or trailing whitespace before adding it to the HashSet.
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.