w3resource

Java Collection, LinkedList Exercises: Convert a linked list to array list

Java Collection, LinkedList Exercises: Exercise-23 with Solution

Write a Java program to convert a linked list to array list.

Sample Solution:-

Java Code:

import java.util.*;

public class Exercise23 {
 public static void main(String[] args) {
  // create an empty linked list
  LinkedList <String> linked_list = new LinkedList <String> ();
            linked_list.add("Red");
          linked_list.add("Green");
          linked_list.add("Black");
          linked_list.add("White");
          linked_list.add("Pink");
          System.out.println("Original linked list: " + linked_list);
   
      //Convert a linked list to array list    
     List<String> list = new ArrayList<String>(linked_list);

    for (String str : list){
      System.out.println(str);
    }
 }
}

Sample Output:

Original linked list: [Red, Green, Black, White, Pink]                 
Red                                                                    
Green                                                                  
Black                                                                  
White                                                                  
Pink

Pictorial Presentation:

Java Collection Linked-list: Convert a linked list to array list.

Flowchart:

Flowchart: Convert a linked list to array list

Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?



Java: Tips of the Day

Choice between Float and Double:

Data type Bytes used Significant figures (decimal)
Float 4 7
Double 8 15

Double is often preferred over float in software where precision is important because of the following reasons:
Most processors take nearly the same amount of processing time to perform operations on Float and Double. Double offers far more precision in the same amount of computation time.

Ref: https://bit.ly/3oj7K2K