beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Append all the elements of a List to LinkedList – Java

By Chaitanya Singh | Filed Under: Java.util package

Description

Program to add all the elements of a List to the LinkedList using addAll() method of LinkedList class.

Example

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
class LinkedListAddAll {

  public static void main(String[] args) {

     // create a LinkedList
     LinkedList<String> list = new LinkedList<String>();

     // Add elements to the LinkedList
     list.add("AA");
     list.add("BB");
     list.add("CC");
     list.add("DD");

     // Displaying linked list before add
     System.out.println("Before: LinkedList: " + list);

     // create a new list having few elements
     List<String> arrayList = new ArrayList<String>();
     arrayList.add("Item1");
     arrayList.add("Item2");
     arrayList.add("Item3");

     // Append the list elements to LinkedList
     list.addAll(arrayList);

     // Displaying the LinkedList after addAll
     System.out.println("After: LinkedList: " + list);
  }
}

Output:

Before: LinkedList: [AA, BB, CC, DD]
After: LinkedList: [AA, BB, CC, DD, Item1, Item2, Item3]

addAll() method:

public boolean addAll(Collection<? extends E> c): Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s iterator. Source: addAll() method – Javadoc.

Enjoyed this post? Try these related posts

  1. Java – Get the index of last occurrence of an element in LinkedList
  2. Convert HashSet to a List/ArrayList
  3. Java – LinkedList poll(), pollFirst() and pollLast() methods
  4. LinkedList push() and pop() methods – Java
  5. Java – How to Sort a HashSet?
  6. Java – LinkedList peek(), peekFirst() and peekLast() methods

Leave a Reply Cancel reply

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

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap