How to find Java LinkedList contains all list elements or not? - Walking Techie

Blog about Java programming, Design Pattern, and Data Structure.

Friday, December 2, 2016

How to find Java LinkedList contains all list elements or not?

LinkedList is doubly-linked list implementation of the List and Deque interfaces.

How to find Java LinkedList contains all list elements or not?

Here we will see an example for finding whether an instance of an LinkedList contains all object of another Collection instance.

package com.walking.techie;

import java.util.ArrayList;
import java.util.LinkedList;

public class LinkedListContainAllDemo {

 public static void main(String[] args) {
  LinkedList<String> numbers = new LinkedList<String>();
  numbers.add("First");
  numbers.add("Second");
  numbers.add("Third");
  numbers.add("Fourth");

  // Another linked list
  LinkedList<String> linkedList = new LinkedList<String>();
  numbers.add("Fourth");
  linkedList.add("First");

  System.out.println(
    "Does numbers LinkedList contains all linkedList elements?: " + numbers.containsAll(linkedList));
  linkedList.add("Zero");
  System.out.println(
    "Does numbers LinkedList contains all linkedList elements?: " + numbers.containsAll(linkedList));
  // ArrayList
  ArrayList<String> arrayList = new ArrayList<String>();
  arrayList.add("Second");
  arrayList.add("Fourth");

  System.out.println("Does numbers LinkedList contains all arrayList elements?: " + numbers.containsAll(arrayList));
 }
}

Output of above program is shown below:

Does numbers LinkedList contains all linkedList elements?: true
Does numbers LinkedList contains all linkedList elements?: false
Does numbers LinkedList contains all arrayList elements?: true

No comments :

Post a Comment