Convert Set of String to Array of String in Java

Java 8Object Oriented ProgrammingProgramming

At first, create a Set of string −

Set<String> setStr = new HashSet<>(Arrays.asList("osCommerce", "PrestaShop", "Magento","Wordpres", "Drupal"));

Now, use the toArray() method to convert to array of string −

String[] arrStr = setStr.toArray(new String[0]);

Example

Following is the program to convert Set of String to Array of String in Java −

import java.util.Arrays;
import java.util.Set;
import java.util.HashSet;
public class Demo {
   public static void main(String[] args) {
      Set<String> setStr = new HashSet<>(
         Arrays.asList("osCommerce", "PrestaShop", "Magento","Wordpres", "Drupal"));
      System.out.println("Set of String: " + setStr);
      String[] arrStr = setStr.toArray(new String[0]);
      System.out.println("Array of String = "+ Arrays.toString(arrStr));
   }
}

Output

Set of String: [Wordpres, Drupal, PrestaShop, osCommerce, Magento]
Array of String = [Wordpres, Drupal, PrestaShop, osCommerce, Magento]
raja
Published on 25-Sep-2019 07:54:01
Advertisements