3

I have an array of which I want to create List with each list have only one element of array. So for array {1,2,3} I want to create 3 List with each having element 1, 2 and 3 respectively.

Have done it using java 7 but wanted to know if it can be solved using java 8 stream, maps etc

Thanks

2
  • 5
    It’s not very hard, using the basics shown in the documentation: for Integer[], you can use List<List<Integer>> list = Arrays.stream(array).map(Collections::singletonList).collect(Collectors.toList());, for an int[], you only have to change map to mapToObj Commented Jan 4, 2017 at 10:20
  • 1
    @Holger Thank you Commented Jan 4, 2017 at 10:31

1 Answer 1

8

This will work:

Integer[] array = {1,2,3};

List<List<Integer>> list = Arrays.stream(array)
                                 .map(Collections::singletonList)
                                 .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

1 Comment

Thank u, was missing Collections::singletonList part.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.