0

Hello Everyone I am beginner in java I want to convert integer array to arraylist and linkedlist in collection framework.I tried but it shows an error.can anyone solve this issue? Thanks in advance....

package com.pac.work;

import java.util.Arrays;

public class checkarraytoarraylist {

    public static void main(String[] args)
    {
        int[] a={10,25,47,85};
        List<Integer> al=new ArrayList<Integer>(Arrays.asList(a));
        System.out.println(al);
        List<Integer> a2=new LinkedList<Integer>(Arrays.asList(a));
        System.out.println(a2);
    }

}
awesoon
  • 32,469
  • 11
  • 74
  • 99
vignesh tokyo
  • 93
  • 1
  • 7
  • 2
    shows "an error", could you be more specific about that part? – Stultuske May 24 '18 at 10:12
  • java 8 `ArrayList list = Arrays.stream(a).boxed().collect(Collectors.toCollection(ArrayList::new)); LinkedList list2 = Arrays.stream(a).boxed().collect(Collectors.toCollection(LinkedList::new));` – prasadmadanayake May 24 '18 at 10:32

4 Answers4

2

You can only use Arrays.asList(a); on class type. In your case Integer.

So it would look like this:

 Integer[] a={10,25,47,85};
    List<Integer> al=Arrays.asList(a);
    System.out.println(al);
    List<Integer> a2=Arrays.asList(a);
    System.out.println(a2);

If there is no possibility to have an Integer[] array, you can copy content from int[] array to Integer[] and then use Arrays.asList();

Moler
  • 955
  • 2
  • 8
  • 17
1

If you are using Java 8 , you can use Streams.

List<Integer> al= Arrays.stream(a).boxed().collect(Collectors.toList());

if not you will have to loop through and add them.

List<Integer> al = new ArrayList<Integer>();
for (int i : a)
{
al .add(a);
}
Dishonered
  • 8,449
  • 9
  • 37
  • 50
0

I think there is no shortcut method to do. All you have to do is loop through each and every elements of array and add to a list, Ya and you may use libraries, one of the popular is guava: - https://github.com/google/guava

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class checkarraytoarraylist {

    public static void main(String[] args)
    {
        int[] a={10,25,47,85};

        List<Integer> al=new ArrayList<Integer>();
        for(int item : a) {
            al.add(item);
        }
        System.out.println(al);
    }

}
Keval Bhatt
  • 152
  • 1
  • 12
0

You can try this one

Integer[] a={10,25,47,85};
List<Integer> al= new ArrayList<Integer>();
System.out.println(al);
List<Integer> a2=new LinkedList<Integer>(Arrays.asList(a));
System.out.println(a2);
Philipp Sander
  • 10,139
  • 6
  • 45
  • 78