-3

Most examples i see here explain how to convert an array of primitives to ArrayList.

Is it possible to use stream() to convert an array of non-primitives into an ArrayList?

If not, is there a utility to do the same ?

Naman
  • 23,555
  • 22
  • 173
  • 290
user1354825
  • 358
  • 3
  • 16
  • 2
    It is possible, just search for your specific type and you would find a relevant duplicate on Stackoverflow as well. – Naman Aug 19 '20 at 00:54
  • 1) Yes. Use the same approach as for an array of primitives. Create a stream from the array and collect into a list. 2) `Arrays.asList(array)` or `new ArrayList(Arrays.asList(array))` – Stephen C Aug 19 '20 at 00:58
  • 1
    Does this answer your question? [Converting array to list in Java](https://stackoverflow.com/questions/2607289/converting-array-to-list-in-java) – 10 Rep Aug 19 '20 at 00:58
  • 1
    General SO question: This is indeed a duplicate of 'Converting array to list in Java'. However, the winning answer on that one has 1400 votes and is, now, in 2020, so misleading it's bordering on wrong (Arrays.asList has downsides, such as being half-immutable and half-mutable, giving you the worst properties of either, and there's the much cleaner List.of now). So how does one tackle that problem? Find 1400 people to downvote it? Seems unfair to the answerer, because at the time they wrote it, that was decent. – rzwitserloot Aug 19 '20 at 01:02
  • @rzwitserloot: [oddly timely](https://meta.stackoverflow.com/questions/400380/what-should-i-do-if-a-question-has-been-asked-and-answered-but-software-and-an) – chrylis -cautiouslyoptimistic- Aug 19 '20 at 02:42
  • 1
    @rzwitserloot these drawbacks do not invalidate the answer. If you want a copying-free solution, `Arrays.asList(…)` still is the solution and its limitations are unavoidable. Of course, it would be good if that answer documented the issues. But mind that this answer is actually answering a different question, i.e. about converting `int[]` to a `List` with the wrong premise that using `Arrays.asList` for that worked prior to Java 5. – Holger Aug 19 '20 at 08:03
  • @Holger Arrays.asList does not now and has never been able to convert int[] to List. – rzwitserloot Aug 19 '20 at 12:15
  • 1
    @rzwitserloot that’s precisely what I said. That linked question has the *wrong* premise… – Holger Aug 19 '20 at 12:50

1 Answers1

2

The trivial answer is of course:

String[] array = ...;
List<String> list = List.of(array);

You mention 'use stream()' - um, why? Stream is a tool. For this job, that's a bit like asking: "Hey, can I hammer in a nail.... using a shoe?". I guess, maybe? Shoes are great if you're going for a run, not appropriate when trying to fasten a nail. Use a hammer.

But if you want to.. sure.. Arrays.stream(array).collect(Collectors.toList());, but this is more typing, slower, less idiomatic, and basically in all ways worse.

rzwitserloot
  • 44,252
  • 4
  • 27
  • 37