How Convert Array to LinkedList

In Previous post we have learn how to convert LinkedList to Array in Java . In This tutorial we will see how to  convert array into linkedlist in java. There are following ways for create new linkedlist from array java .

  1. Arrays.asList()
  2. Collections.addAll()
  3. add() method

Method 1. Conversion array to Linkedlist using Arrays.asList()

Arrays.asList() Method returns a fixed-size list backed by the specified array in java . This returned list we use in creating LinkedList in java . Let’s see this by code

import java.util.Arrays;
import java.util.LinkedList;

public class ArrayToLinkedList {

public static void main(String[] args) {
	String [] arr = {"java","php" ,"spring","mysql","android"};
		
		/*
		creating linkedlist  using list
		return by Arrays.asList(arr)
		*/
   LinkedList<String> linkedList = new LinkedList<String>(Arrays.asList(arr));
		
		//print linkedList
   System.out.println("linkedList is = "+ linkedList);
		
	}
}

Output :

linkedList is = [java, php, spring, mysql, android]

Method 2. Conversion array to Linkedlist using Collections.addAll()

Adds all of the specified elements to the given collection read more about Collection.addAll() Method here

import java.util.Collections;
import java.util.LinkedList;

public class ArrayToLinkedListByAllAdd {

	public static void main(String[] args) {
	
		String [] arr = {"java","php" ,"spring","mysql","android"};
		
		LinkedList<String> linkedList = new LinkedList<String>();

		/*
            Adds all of the specified elements to the
             specified collection.
		 */
		Collections.addAll(linkedList,arr);
	
		System.out.println("linkedList is ="+ linkedList);

	}
	
}

Output :

linkedList is =[java, php, spring, mysql, android]

Method 3. Convert Array to LinkedList using add() method

In order to create Linkedlist we iterate array and one by one add element in Linkedlist

import java.util.LinkedList;

public class ArrayToLinkedListByAdd {

	public static void main(String[] args) {
        String [] arr = {"java","php" ,"spring","mysql","android"};
		
		LinkedList<String> linkedList = new LinkedList<String>();
		
		//add array element in linkedList one by one using add()
		for (int i = 0; i < arr.length; i++) {
			linkedList.add(arr[i])	;
		}
		
		//print linkedList
		System.out.println("list is ="+linkedList);
		
	}
	
}

Output :

list is =[java, php, spring, mysql, android]

A Guide to LinkedList

 

Leave a Reply

Your email address will not be published. Required fields are marked *

4 + 2 =