0% found this document useful (0 votes)
26 views

Java List Interface

The document discusses Java lists and their classes and methods. It describes ArrayLists, LinkedLists, Vectors and Stacks. It provides examples of creating lists, adding and accessing elements, converting between lists and arrays, sorting lists, and comparing lists.

Uploaded by

antimbhowal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Java List Interface

The document discusses Java lists and their classes and methods. It describes ArrayLists, LinkedLists, Vectors and Stacks. It provides examples of creating lists, adding and accessing elements, converting between lists and arrays, sorting lists, and comparing lists.

Uploaded by

antimbhowal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Java List Interface

A list is an interface of java collections that helps in storing and processing of elements.
➔ It is an ordered collection
➔ It can contain duplicate elements
➔ It can have null elements.
List has the following classes:
➔ Arraylist - The ArrayList class implements the List interface. It uses a dynamic
array to store the duplicate element of different data types. The ArrayList class
maintains the insertion order and is non-synchronized. The elements stored in the
ArrayList class can be randomly accessed.
➔ Linkedlist - LinkedList implements the Collection interface. It uses a doubly linked
list internally to store the elements. It can store the duplicate elements. It maintains
the insertion order and is not synchronized. In LinkedList, the manipulation is fast
because no shifting is required.
➔ Vector - Vector uses a dynamic array to store the data elements. It is similar to
ArrayList. However, It is synchronized and contains many methods that are not the
part of Collection framework.
➔ Stack - The stack is the subclass of Vector. It implements the last-in-first-out data
structure, i.e., Stack. The stack contains all of the methods of Vector class and
also provides its methods like boolean push(), boolean peek(), boolean
push(object o), which defines its properties.

How to create a list:


//Creating a List of type String using ArrayList
List<String> list=new ArrayList<String>();

//Creating a List of type Integer using ArrayList


List<Integer> list=new ArrayList<Integer>();

//Creating a List of type Book using ArrayList


List<Book> list=new ArrayList<Book>();

//Creating a List of type String using LinkedList


List<String> list=new LinkedList<String>();
Basic List programs
Adding and printing using a list:
import java.util.*;
public class ListExample1{
public static void main(String args[]){
//Creating a List
List<String> list=new ArrayList<String>();
//Adding elements in the List
list.add("Mango");
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Iterating the List element using for-each loop
for(String i:list)
System.out.println(i); } }

Converting Array to list


import java.util.*;
public class ArrayToListExample{
public static void main(String args[]){
//Creating Array
String[] array={"Java","Python","PHP","C++"};
System.out.println("Printing Array: "+Arrays.toString(array)); //standard library
function to print array without using loop
//Converting Array to List
List<String> list=new ArrayList<String>();
for(String i:array){
list.add(lang);
}
System.out.println("Printing List: "+list); }
}

Output:
Printing Array: [Java, Python, PHP, C++]
Printing List: [Java, Python, PHP, C++]

Converting list to array


import java.util.*;
public class ListToArrayExample{
public static void main(String args[]){
List<String> fruitList = new ArrayList<String>();
fruitList.add("Mango");
fruitList.add("Banana");
fruitList.add("Apple");
fruitList.add("Strawberry");
//Converting ArrayList to Array
String[] array = new String[fruitList.size()]; //declaring with size as this is
array
fruitList.toArray(array);
System.out.println("Printing Array: "+Arrays.toString(array));
System.out.println("Printing List: "+fruitList);} }
Output:
Printing Array: [Mango, Banana, Apple, Strawberry]
Printing List: [Mango, Banana, Apple, Strawberry]

Get and set element in list


import java.util.*;
public class ListExample2{
public static void main(String args[]){
//Creating a List
List<String> list=new ArrayList<String>();
//Adding elements in the List
list.add("Mango");
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//accessing the element
System.out.println("Returning element: "+list.get(1));//it will return the 2nd eleme
nt, because index starts from 0
//changing the element
list.set(1,"Dates");
//Iterating the List element using for-each loop
for(String i:list)
System.out.println(i); } }

Output:
Returning element: Apple
Mango
Dates
Banana
Grapes

Sorting list

import java.util.*;
class SortArrayList{
public static void main(String args[]){
//Creating a list of fruits
List<String> list1=new ArrayList<String>();
list1.add("Mango");
list1.add("Apple");
list1.add("Banana");
list1.add("Grapes");
//Sorting the list
Collections.sort(list1);
//Traversing list through the for-each loop
for(String fruit:list1)
System.out.println(fruit);

System.out.println("Sorting numbers...");
//Creating a list of numbers
List<Integer> list2=new ArrayList<Integer>();
list2.add(21);
list2.add(11);
list2.add(51);
list2.add(1);
//Sorting the list
Collections.sort(list2);
//Traversing list through the for-each loop
for(Integer number:list2)
System.out.println(number); } }

Output:
Apple
Banana
Grapes
Mango
Sorting numbers...
1
11
21
51

List iterator interface


import java.util.*;
public class ListIteratorExample1{
public static void main(String args[]){
List<String> al=new ArrayList<String>();
al.add("Amit");
al.add("Vijay");
al.add("Kumar");
al.add(1,"Sachin");
ListIterator<String> itr=al.listIterator();
System.out.println("Traversing elements in forward direction");
while(itr.hasNext()){

System.out.println("index:"+itr.nextIndex()+" value:"+itr.next());
}
System.out.println("Traversing elements in backward direction");
while(itr.hasPrevious()){

System.out.println("index:"+itr.previousIndex()+" value:"+itr.previous());
} } }

Output:
Traversing elements in forward direction
index:0 value:Amit
index:1 value:Sachin
index:2 value:Vijay
index:3 value:Kumar
Traversing elements in backward direction
index:3 value:Kumar
index:2 value:Vijay
index:1 value:Sachin
index:0 value:Amit

Removing duplicates form Arraylist


To remove dupliates from ArrayList, we can convert it into Set. Since Set doesn't contain
duplicate elements, it will have only unique elements.

public class RemoveDuplicateArrayList {


public static void main(String[] args) {
List<String> l = new ArrayList<String>();
l.add("Mango");
l.add("Banana");
l.add("Mango");
l.add("Apple");
System.out.println(l.toString());
Set<String> s = new LinkedHashSet<String>(l);
System.out.println(s);
} }

Output:
Before converting to set
[Mango, Banana, Mango, Apple]
After converting to set
[Mango, Banana, Apple]
Reversing Arraylist
The reverse method of Collections class can be used to reverse any collection. It is a
static method. Let's see the signature of reverse method.

public class ReverseArrayList {


public static void main(String[] args) {
List<String> l = new ArrayList<String>();
l.add("Mango");
l.add("Banana");
l.add("Mango");
l.add("Apple");
System.out.println("Before Reversing");
System.out.println(l.toString());
Collections.reverse(l);
System.out.println("After Reversing");
System.out.println(l);
} }
Output:
Before Reversing
[Mango, Banana, Mango, Apple]
After Reversing
[Apple, Mango, Banana, Mango]

How to Compare Two ArrayList in Java


There are following ways to compare two ArrayList in Java:
o Java equals() method
o Java removeAll() method
o Java retainAll() method
o Java ArrayList.contains() method
o Java contentEquals() method
o Java Stream interface

Java equals() method


Java equals() method of List interface compares the specified object with the list for
equality. It overrides the equals() method of Object class.

In the following example, we have create two ArrayList firstList and secondList.
Comparing both list by using equals() method, it returns true. We have added another
element in the secondList to create a difference between firstList and secondList. Now,
if we perform comparison, it returns false.

import java.util.*;
public class ComapreArraylistExample1
{
public static void main(String args[])
{
//first array list
ArrayList<String> firstList=new ArrayList<String>();
//adds elements to the arraylist
firstList.add("Apple");
firstList.add("Pears");
firstList.add("Guava");
firstList.add("Mango");
System.out.println(firstList);
//second array list
List<String> secondList=new ArrayList<String>();
//adds elements to the arraylist
secondList.add("Apple");
secondList.add("Pears");
secondList.add("Guava");
secondList.add("Mango");
System.out.println(secondList);
//comparing both lists
boolean boolval = firstList.equals(secondList); //returns true because lists are
equal
System.out.println(boolval);
//adding another element in the second list
secondList.add("Papaya");
//again comparing both lists
boolean bool = firstList.equals(secondList); //returns false because lists are not
equal
System.out.println(bool); } }

Java removeAll() method


Java removeAll() method of ArrayList class is used to remove all elements from the list
that are contained in the specified collection. It overrides the removeAll() method
of AbstractCollection<E> class.

In the following example, we have created two ArrayList firstList and secondList.
The removeAll() method removes all the elements of the firstList because the same
elements are also present in the secondList, except Papaya. So, Papaya is the missing
element in the firstList. Hence, it returns Papaya. The method returns an empty list [] if
both the list have same elements.

import java.util.*;
public class ComapreArraylistExample2
{
public static void main(String args[])
{
//first arraylist
ArrayList<String> firstList=new ArrayList<String>();
//adds elements to the array list
firstList.add("Apple");
firstList.add("Pears");
firstList.add("Guava");
firstList.add("Peach");
//second array list
ArrayList<String> secondList=new ArrayList<String>();
//adds elements to the array list
secondList.add("Apple");
secondList.add("Pears");
secondList.add("Papaya");
secondList.add("Peach");
//removes all elements from the first list
/returns empty list if all the elements of first list match with elements of second list

secondList.removeAll(firstList);
//prints the element of second list which does not match with the element of the
first list
System.out.println(secondList); } }

Output:
[Papaya]

Let's see another example of removeAll() method that returns the elements from firstList
which are not present is the secondList.

import java.util.*;
public class ComapreArraylistExample3
{
public static void main(String args[])
{
//first array list
ArrayList<Integer> firstList=new ArrayList<Integer>(Arrays.asList(12, 4, 67, 90, 3
4));
System.out.println("First array list: ");
System.out.println(firstList);
//second array list
List<Integer> secondList=new ArrayList<Integer>(Arrays.asList(12, 4, 67, 0, 34));

System.out.println("Second array list: ");


System.out.println(secondList);
//returns the common elements in both list
firstList.removeAll(secondList);
System.out.println("Un-common element of the first list: ");
System.out.println(firstList);
} }

Output:
First array list:
[12, 4, 67, 90, 34]
Second array list:
[12, 4, 67, 0, 34]
Un-common element of the first list:
[90]

Java retainAll() method


Java retainAll() method of ArrayList class retains only the elements of the list that are
contained in other list also. It overrides the retainAll() method
of AbstarctCollection<E> class.

In this example, we have created two ArrayList firstList and secondList by using
the asList() method of the Arrays class. The asList() method returns a list view of the
specified array.
import java.util.*;
public class ComapreArraylistExample4
{
public static void main(String args[])
{
//first arraylist
ArrayList<String> firstList=new ArrayList<String>(Arrays.asList("M", "W", "J", "K",
"T"));
System.out.println("First arraylist: ");
System.out.println(firstList);
//second arraylist
List<String> secondList=new ArrayList<String>(Arrays.asList("M", "W", "E", "K", "
T"));
System.out.println("Second arraylist: ");
System.out.println(secondList);
//returns the common elements in both list
secondList.retainAll(firstList);
System.out.println("Common elements in both list: ");
System.out.println(secondList);
} }

Output:
First arraylist:
[M, W, J, K, T]
Second arraylist:
[M, W, E, K, T]
Common elements in both list:
[M, W, K, T]
Java ArrayList.contains() method

Java ArrayList.contains() method is used for comparing two elements of different


ArrayList. Java ArrayList.contains() method overrides the contains() method
of AbstrarctCollection<E> class.

In this example, we have created two ArrayList firstList and secondList of String type.
We have compared these ArrayList using contains() method. If the elements of firstList
match with the elements of the secondList, it return Yes and stores this value
into thirdList. Similarly, if the element does not match, it return No.

import java.util.ArrayList;
import java.util.Arrays;
public class ComapreArraylistExample5
{
public static void main(String [] args)
{
//first arraylist
ArrayList<String> firstList= new ArrayList<String>(Arrays.asList("Good", "Mornin
g", "Students"));
//second arraylist
ArrayList<String> secondList= new ArrayList<String>(Arrays.asList("Good", "Nig
ht", "frineds"));
//storing the comparison output in thirdList
ArrayList<String> thirdList= new ArrayList<String>();
//iterator using for-each loop
for(String tempList : firstList) //tempList is a variable
thirdList.add(secondList.contains(tempList) ? "Yes" : "No");
System.out.println(thirdList);
} }

Output:
[Yes, No, No]

Java contentEquals() method

Java contentEquals() method compares the String with the StringBuffer and returns
a boolean value. It belongs to String class.
In this example, we have created two ArrayList firstList and secondList of String type.
We have created a static method compareList() which parses two
ArrayList ls1 and ls2 as an argument and returns a boolean value. The method converts
a list into String. The contentEquals() method compares the String to the specified
StringBuffer.
We have added another element in the secondList to create the difference between both
lists and again call the compareList() method, which returns false.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ComapreArraylistExample6
{
//defining method
public static boolean compareList(ArrayList ls1, ArrayList ls2)
{
//converts List into String and checks string are equal or not
return ls1.toString().contentEquals(ls2.toString())?true:false;
}
public static void main(String[] args)
{
ArrayList<String> firstList = new ArrayList<String>(Arrays.asList("Java", "Python"
, "Ruby", "Go"));
ArrayList<String> secondList = new ArrayList<String>(Arrays.asList("Java", "Pyt
hon", "Ruby", "Go"));
System.out.println("When Lists are same: "+compareList(firstList, secondList));
//adding another element to the secondList
secondList.add("C++");
//output after adding different element
System.out.println("When Lists are not same: "+compareList(firstList, secondList)
); } }

Output:
When Lists are same: true
When Lists are not same: false

Java Collections.reverseOrder() method

It is the method of Java Collections class which belong to a java.lang package. It returns
a comparator that imposes reverse of the natural ordering.

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class SortListExample4
{
public static void main(String args[])
{
List<Integer> list = Arrays.asList(10,1,-20,40,5,-23,0);
Collections.sort(list, Collections.reverseOrder());
System.out.println(list);
} }

Java Collections.sort() method


The sort() method sorts the list in ascending order, according to the natural ordering of its
elements.

import java.util.*;
public class SortListExample5
{
public static void main(String[] args)
{
List<String> sList = new ArrayList<String>();
sList.add("m");
sList.add("k");
sList.add("a");
sList.add("p");
sList.add("d");
Collections.sort(sList); //sorts array list
for(String str: sList)
System.out.print(" "+str);
} }

You might also like