How to concatenate lists into one list

  • A+
Category:Languages

I have a list of values, some of which could be lists/collections or single values. In JavaScript notation it might look like:

const input = [1,2,[3,4], [5,6], 7]; 

and I want to get:

const concatenated = [1,2,3,4,5,6,7]; 

So I have this Java code:

      ArrayList<T> concatenated = new ArrayList<>();        for (T v : input) {         try{           concatenated.addAll((Collection) v);         }         catch (Exception e1){           try{             concatenated.addAll((List) v);           }           catch (Exception e2){             concatenated.add(v);           }         }       } 

but that code seems pretty terrible to me. First I don't know if attempting to cast to List or Collection is sufficient - are there are other types I should attempt to cast to? Are there any errors I shouldn't ignore?

How to do this right?

 


The code doesn't need Exception handling as such unless there are null values in the lists. It should be sufficient though in your case to just cast basis of instanceOf as:

// Edit: Since the type of the input `Collection` is not bound strictly List<Object> flatten(Collection<?> input) {     List<Object> concatenated = new ArrayList<>();     for (Object v : input) {         if (v instanceof Collection) {             concatenated.addAll(flatten((Collection<?>) v));         } else {             concatenated.add(v);         }     }     return concatenated; }  

using it further on jshell gives me this output:

jshell> List<Object> list = List.of(1,2,List.of(3,4),List.of(5,6),7)  list ==> [1, 2, [3, 4], [5, 6], 7]  jshell> flatten(list) $3 ==> [1, 2, 3, 4, 5, 6, 7] 

:

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: