programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Jeanne Boyarsky
• Ron McLeod
• Paul Clapham
• Liutauras Vilda
Sheriffs:
• paul wheaton
• Rob Spoor
• Devaka Cooray
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Carey Brown
• Frits Walraven
• Tim Moores
Bartenders:
• Mikalai Zaikin

# Best way to flatten a list

Ranch Hand
Posts: 46
1
• Number of slices to send:
Optional 'thank-you' note:
Hi all,

Using java 7,
What would the best method be to flatten an array such as:
[1, [2, 3], [4, [5, [6, 7], 8], 9], 10]

So that the output is [1,2,3,4,5,6,7,8,9,10]

Currently I am stuck trying to iterate this array.

Many thanks

author
Posts: 23956
142
• Number of slices to send:
Optional 'thank-you' note:

Since the list can go to any depth, the easiest way, in my opinion, is to do it recursively.

Henry

Kyle Jones
Ranch Hand
Posts: 46
1
• Number of slices to send:
Optional 'thank-you' note:
Thanks for the reply, i will look at doing this recursively.

Probably a noob question but how could I instantiate an array of this type?

[1, [2, 3], [4, [5, [6, 7], 8], 9], 10]

Bartender
Posts: 5478
212
• 1
• Number of slices to send:
Optional 'thank-you' note:
A possibility would be:

greetz,
Piet

Piet Souris
Bartender
Posts: 5478
212
• Number of slices to send:
Optional 'thank-you' note:
Didn't want to end up with 911 posts ;)

Greetz,
Piet

Kyle Jones
Ranch Hand
Posts: 46
1
• Number of slices to send:
Optional 'thank-you' note:
Here is my solution using recursion. Thanks Henry

I am now looking at easier solutions using Java 8 functionalities.

Henry Wong
author
Posts: 23956
142
• Number of slices to send:
Optional 'thank-you' note:

Thanks for coming back and reporting the answer ... you earned a cow.

Henry

Marshal
Posts: 79471
379
• Number of slices to send:
Optional 'thank-you' note:

Piet Souris wrote:Didn't want to end up with 911 posts ;)

Greetz,
Piet

You mean only 88 more to go ?

Kyle Jones
Ranch Hand
Posts: 46
1
• Number of slices to send:
Optional 'thank-you' note:

Henry Wong wrote:
Thanks for coming back and reporting the answer ... you earned a cow.

Henry

Thanks for the cow

I am looking to write tests for this function, this is my cuurent test:

Any other functionalities that could be tested here, or improvements on the above?

Thanks

Saloon Keeper
Posts: 15630
366
• Number of slices to send:
Optional 'thank-you' note:
For Java 8, you can do this using Streams. Implement the following method:

Hint: take a look at Stream.flatMap()

 With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.