Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten out a list in java

Tags:

People also ask

How do I flatten a list in Java 8?

The standard solution is to use the Stream. flatMap() method to flatten a List of Lists. The flatMap() method applies the specified mapping function to each element of the stream and flattens it.

How do you flatten an array of objects in Java?

Create an empty list to collect the flattened elements. With the help of forEach loop, convert each elements of the array into stream and add it to the list. Now convert this list into stream using stream() method. Now flatten the stream by converting it into array using toArray() method.

What does flatten mean Java?

In very layman's terms, flattening is referred to as merging multiple collections/arrays into one. Consider the following example. In this example, we have an array of 3 arrays. After the flattening effect, we will have one result array with all the items from the 3 arrays.

How can I turn a list of lists into a list in Java 8?

Here is the simple, concise code to perform the task. // listOfLists is a List<List<Object>>. List<Object> result = new ArrayList<>(); listOfLists. forEach(result::addAll);


I was asked this question in an interview

Given a hypothetical list in java that, along with holding integer content, may also hold another list of similar type

Example: [1,3,5,[6,7],8,9,10,[11,13,15,[16,17,[18,19]]],20]

Output should be:

[1,3,5,6,7,8,9,10,11,13,15,16,17,18,19,20]

Easy I thought! So i came with a recursive solution that solved the problem! Or not?

The interviewer said sublists could go down to any depths and hence may result in stackoverflow error!

I tried coming up with a non recursive solution, but couldn't. Could anyone tell what that non recursive solution might be?