-1

I have a List something like this:

List<String> name = [[tom,john,peter,richered][manoj,satya,sachin,andrew]]

How would I convert it into a single ArrayList, using stream

2
  • Possible Duplicate : stackoverflow.com/questions/10910312/… Commented Dec 26, 2017 at 9:12
  • 1
    Downvote for posting non-compiling sample code without specifying input and output and then complaining the answers do not fit. Commented Dec 26, 2017 at 9:47

2 Answers 2

2

You can use flatMap in Java8,

List<List<String>> main = new ArrayList<>();
List<String> l1 = Arrays.asList("1", "2");
List<String> l2 = Arrays.asList("3", "4");
main.add(l1);
main.add(l2);
List<String> ans = main.stream()
                       .flatMap(list -> list.stream())
                       .collect(Collectors.toList());
System.out.println(ans);

OUTPUT

[1, 2, 3, 4]
Sign up to request clarification or add additional context in comments.

8 Comments

In case if you don't know the input that you are entering asList, how would you achieve this output.
This is just to prepare lists quickly for example. Notice the important part where list of list is processed to get list named ans.
ans is absolutely fine, but its not relevant to my code: consider this again [[tom,john,peter,richered][manoj,satya,sachin,andrew]] here I can separate these lists into sublist but I would not be use subList in the code provided by you.
Okay. Can you add more code or explanation to your question, please? It'll be really helpful to track down the exact problem.
Alright, your code is absolute fine, earlier I was using substrings and when I was adding them to the array list using add(subString), it was giving me compile time error, now I realize I don't have to use substrings I only need to use the stream one code. My Apology and thanks for your help.
|
1

Use flatMap:

List<List<String>> name = Lists.newArrayList(Lists.newArrayList("a", "b", "c", "d"), Lists.newArrayList("e", "f", "g"));

List<String> namesTogether = name.stream().flatMap(Collection::stream).collect(Collectors.toList());

System.out.println(namesTogether);

[a, b, c, d, e, f, g]

3 Comments

Answer is not relevant to my question, please consider other comments
@SanatSingh No, I will not "consider other comments", this is the exact answer to your question. This (in the same way as the other answer) "converts a list having sub-lists into a single list using java 8 streams".
Alright, your code is absolute fine, earlier I was using substrings and when I was adding them to the array list using add(subString), it was giving me compile time error, now I realize I don't have to use substrings I only need to use the stream one code. please accept my apology and thanks for your help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.