0

I'm looking for the simplest way to convert int[] to LinkedList in java

I know something like this probably works, but is there a simpler way?

Integer[] m = new Integer[n];
for(int i=0; i<n; i++) {
    m[i] = new Integer(nums[n]);
}

LinkedList<Integer> l = Arrays.asList(m);
user511792
  • 489
  • 1
  • 13
  • 23
  • duplicate: http://stackoverflow.com/questions/1073919/how-to-convert-int-into-listinteger-in-java – DanielM Aug 13 '14 at 17:47
  • not really a duplicate as it is about converting to a LinkedList, not a List in general. – isnot2bad Aug 13 '14 at 17:55
  • First, thanks to @djechlin for actually linking to the duplicate question. Very few "closers cause it's duplicate" do so. Second, the "official checked answer" to the cited duplicate question is wrong, cause it converts to an array of Longs, not a List. But some of the other answers are correct. – user949300 Aug 13 '14 at 17:58
  • Since Java 8, you can use streams for that too: `Arrays.stream(arr).map(Integer::valueOf).collect(Collectors.toList())` – isnot2bad Aug 13 '14 at 18:00
  • @isnot2bad doesn't matter, the answers work. Close as duplicate even if the questions appear different, if target answer works on source question. If this is *not* the case, the burden is on the OP to explain why the target answers do *not* apply by editing the question, then reopen. – djechlin Aug 13 '14 at 20:52
  • @user949300 see above comment. Further the "official checked answer" is not "official," it's the one the OP checked, presumably because they found it most useful (perhaps the OP decided an array works just as well). – djechlin Aug 13 '14 at 20:52

1 Answers1

4

Just adding them to the list (by iterating) is simpler. LinkedList<..> has O(1) add (to end), so you don't have to worry about time efficiency - the whole operation will be O(n) and you can't get better than that for this operation.

public LinkedList<Integer> toList(int[] arr){
    LinkedList<Integer> l = new LinkedList<Integer>();
    for(int i : arr)
        l.add(i);
    return l;
}
Mshnik
  • 7,032
  • 1
  • 25
  • 38