Is there any Utility function in Java to convert List<Object[]> to List<Object>
-
3describe you question properlyBhargav Modi– Bhargav Modi2014-12-22 14:23:37 +00:00Commented Dec 22, 2014 at 14:23
-
The question is ambiguous: what should happen if an array contains two or more elements? Please provide an example.willeM_ Van Onsem– willeM_ Van Onsem2014-12-22 14:24:10 +00:00Commented Dec 22, 2014 at 14:24
-
What would you expect as a result from that function?Predrag Maric– Predrag Maric2014-12-22 14:24:13 +00:00Commented Dec 22, 2014 at 14:24
-
No, there is no such method available. Either iterate over the list and each array and add the entries into a new list or use one of the fancy Java 8 Streams.Tom– Tom2014-12-22 14:25:34 +00:00Commented Dec 22, 2014 at 14:25
-
@rams, feel free to review the answers and accept the one the best answers your question.aioobe– aioobe2015-01-23 10:40:05 +00:00Commented Jan 23, 2015 at 10:40
Add a comment
|
5 Answers
You can easily write one yourself:
public static<T> List<T> append (List<T[]> input) {
List<T> res = new ArrayList<T>();
for(T[] subarr : input) {
if(subarr != null) {
int n = subarr.length;
for(int i = 0; i < n; i++) {
res.add(subarr[i]);
}
}
}
return res;
}
The function appends the different arrays and null arrays are ignored, null elements are however not. Thus if the input is [null,[a,b],[null,null],[c,null,d],null]. The output is [a,b,null,null,c,null,d].
4 Comments
Tom
new List<T>()? Since when can you instantiate an interface? But besides that, I like that you're checking for null.willeM_ Van Onsem
@Tom: True, modified it. In C#,
List<T> is a class :(. Sometimes one starts mixing up std-libs... :sLouis Wasserman
Why allow null arrays? Null arrays seem likely to indicate a bug earlier in the program...?
willeM_ Van Onsem
@LouisWasserman:
null arrays are ignored. Simply because some people see them as zero-length arrays. It is of course arbitrary. But in case null shouldn't be allowed, one can simply remove the if clause.As others have already said, there is no utility and creating one yourself wouldn't be hard, for example using old school for loops:
public List<Object> flatten( List<Object[]> source )
{
// if ( source == null ) return null; // which check you use it up to you
List<Object> result = new ArrayList<Object>();
if ( source == null ) return result; // Personally I like this check
for ( Object[] array: source )
{
if ( array == null ) continue; // skip nulls
for ( Object object: array )
{
result.add(object);
}
}
return result;
}