I need to convert List<List<Integer>> listoflist
into int[] arr
. Straightforward solution is to use for
loops, but is there a better approach?
Asked
Active
Viewed 89 times
0
![](../../users/profiles/2422776.webp)
Mureinik
- 252,575
- 45
- 248
- 283
![](../../users/profiles/1089623.webp)
Klausos Klausos
- 12,932
- 43
- 120
- 206
-
The approach would still be the same – redFIVE Dec 21 '15 at 18:02
-
3`list.stream().flatMap(l -> l.stream()).mapToInt(i -> i.intValue()).toArray()` . I wish the question wasn't closed as duplicate @redFIVE – sidgate Dec 21 '15 at 18:10
-
@sidgate: Is it Java 8? I am using Java 7. – Klausos Klausos Dec 21 '15 at 18:13
-
yes, java-8. don't have any better approach for Java 7 – sidgate Dec 21 '15 at 18:14
-
2@sidgate beat me to it - ping me after you post this as an answer and I'd upvote. IMHO, though, using function references would be neater - `list.stream().flatMap(List::stream).mapToInt(Integer::intValue).toArray();` – Mureinik Dec 21 '15 at 18:14
-
@Mureinik yep much better – sidgate Dec 21 '15 at 18:17
-
@Mureinik http://stackoverflow.com/questions/18290935/flattening-a-collection looks like a much saner Java 8 flattening approach, without the double streaming – pvg Dec 21 '15 at 18:19
-
possible dupe of http://stackoverflow.com/questions/18290935/flattening-a-collection – pvg Dec 21 '15 at 18:19
-
@Mureinik: What is 'listoflist' and 'arr' in this line of code? – Klausos Klausos Dec 21 '15 at 18:22
-
@KlausosKlausos - add `int[] arr = ` to the beginning, and change `list.stream()` to `listoflist.stream()`. – nickb Dec 21 '15 at 18:23
-
@KlausosKlausos `list` should be `listoflist`, right. This line returns the array, so you could do something like `int[] arr = listoflistsstream().flatMap(List::stream).mapToInt(Integer::intValue).toArray();` – Mureinik Dec 21 '15 at 18:23
-
@pvg though this question seems similar, it has a different solution and gives better alternative to age old problem of converting to primitive array – sidgate Dec 21 '15 at 18:24