Reputation: 15519
How can I convert a Set<Set<String>>
to a String[][]
? I have tried .toArray(new String[0])
but this doesn't seem to do the trick.
Thanks! Christian
Upvotes: 1
Views: 1509
Reputation: 7016
Try below code, it works
package com.rais;
import java.util.HashSet;
import java.util.Set;
/**
* @author Rais.Alam
* @date Dec 17, 2012
*/
public class SetClient
{
/**
* @param args
*/
public static void main(String[] args)
{
Set<Set<String>> myArray = new HashSet<Set<String>>();
Set<String> arr1 = new HashSet<String>();
Set<String> arr2 = new HashSet<String>();
Set<String> arr3 = new HashSet<String>();
arr1.add("a-1");
arr1.add("a-2");
arr1.add("a-3");
arr2.add("b-1");
arr2.add("b-2");
arr2.add("b-3");
arr3.add("c-1");
arr3.add("c-2");
arr3.add("c-3");
arr3.add("c-4");
arr3.add("c-5");
myArray.add(arr1);
myArray.add(arr2);
myArray.add(arr3);
String[][] outputArray = convertSetOfSetToArray(myArray);
for (String[] outerArr : outputArray)
{
for (String value : outerArr)
{
if (value != null)
{
System.out.println(value);
}
}
}
}
public static String[][] convertSetOfSetToArray(Set<Set<String>> myArray)
{
int secondArraySize = 0;
/*
* Looping array to get the size.
*/
for (Set<String> innerSet : myArray)
{
if (innerSet.size() > secondArraySize)
{
secondArraySize = innerSet.size();
}
}
// Declaring and initializing String arrays;
String[][] outputArray = new String[myArray.size()][secondArraySize];
int firstIndex = 0;
int secondIndex = 0;
for (Set<String> innerSet : myArray)
{
for (String value : innerSet)
{
outputArray[firstIndex][secondIndex] = value;
secondIndex++;
}
secondIndex = 0;
firstIndex++;
}
return outputArray;
}
}
Upvotes: 0
Reputation: 11818
For each Set<String> s
in the outer set, convert s
to String[]
and add it to your Array of arrays.
I don't know any built in way to create n-dimensional arrays from nested collections.
Upvotes: 4