List in Java

 Source: https://facingissuesonit.com/2019/10/15/java-collection-framework-hierarchy/

  • Java List interface is a member of the Java Collections Framework.

  • List allows you to add duplicate elements.

  • List allows you to have ‘null’ elements.

  • List interface got many default methods in Java 8, for example replaceAll, sort and spliterator.

  • List indexes start from 0, just like arrays.

Java List Methods

Some of the useful Java List methods are;

  1. int size(): to get the number of elements in the list.

  2. boolean isEmpty(): to check if list is empty or not.

  3. boolean contains(Object o): Returns true if this list contains the specified element.

  4. Iterator<E> iterator(): Returns an iterator over the elements in this list in proper sequence.

  5. Object[] toArray(): Returns an array containing all of the elements in this list in proper sequence

  6. boolean add(E e): Appends the specified element to the end of this list.

  7. boolean remove(Object o): Removes the first occurrence of the specified element from this list.

  8. boolean retainAll(Collection<?> c): Retains only the elements in this list that are contained in the specified collection.

  9. void clear(): Removes all the elements from the list.

  10. E get(int index): Returns the element at the specified position in the list.

  11. E set(int index, E element): Replaces the element at the specified position in the list with the specified element.

  12. ListIterator<E> listIterator(): Returns a list iterator over the elements in the list.

  13. List<E> subList(int fromIndex, int toIndex): Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa.

Java Array to List

We can use Arrays class to get the view of array as list. However we won’t be able to do any structural modification to the list, it will throw java.lang.UnsupportedOperationException. So the best way is to use for loop for creating list by iterating over the array. Below is a simple example showing how to convert java array to list properly.

Java Arrays to List:

package com.journaldev.examples;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

public class ArrayToList {

public static void main(String[] args) {

String[] vowels = {"a","e","i","o","u"};

List<String> vowelsList = Arrays.asList(vowels);

System.out.println(vowelsList);

/**

* List is backed by array, we can't do structural modification

* Both of the below statements will throw java.lang.UnsupportedOperationException

*/

//vowelsList.remove("e");

//vowelsList.clear();

//using for loop to copy elements from array to list, safe for modification of list

List<String> myList = new ArrayList<>();

for(String s : vowels){

myList.add(s);

}

System.out.println(myList);

myList.clear();

}

}




























Java List to Array:


package com.journaldev.examples;


import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;


public class ListToArray {


public static void main(String[] args) {


List<String> letters = new ArrayList<String>();


// add example

letters.add("A");

letters.add("B");

letters.add("C");

//convert list to array

String[] strArray = new String[letters.size()];

strArray = letters.toArray(strArray);

System.out.println(Arrays.toString(strArray)); //will print "[A, B, C]"

}


}



List Sort:


package com.journaldev.examples;


import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

import java.util.Random;


public class ListSortExample {


public static void main(String[] args) {

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

Random random = new Random();

for (int i = 0; i < 10; i++) ints.add(random.nextInt(1000));

//natural sorting using Collections class

Collections.sort(ints);

System.out.println("Natural Sorting: "+ints);

//My custom sorting, reverse order

ints.sort((o1,o2) -> {return (o2-o1);});

System.out.println("Reverse Sorting: "+ints);

}

}







Common List Operations:



package com.journaldev.examples;


import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;


public class ListExample {


public static void main(String args[]) {

List<String> vowels= new ArrayList<String>();

//add example

vowels.add("A");

vowels.add("I");

//let's insert E between A and I

vowels.add(1,"E");

System.out.println(vowels);

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

list.add("O");list.add("U");

//appending list elements to letters

vowels.addAll(list);

System.out.println(vowels);

//clear example to empty the list

list.clear();

//size example

System.out.println("letters list size = "+vowels.size());

//set example

vowels.set(2, "E");

System.out.println(vowels);

//subList example

vowels.clear();vowels.add("E"); vowels.add("E");vowels.add("I"); vowels.add("O");

list = vowels.subList(0, 2);

System.out.println("letters = "+vowels+", list = "+list);

vowels.set(0, "A");

System.out.println("letters = "+vowels+", list = "+list);

list.add("U");

System.out.println("letters = "+vowels+", list = "+list);

}


}


Output:



Java List iterator:



package com.journaldev.examples;


import java.util.ArrayList;

import java.util.Iterator;

import java.util.List;


public class ListIteratorExample {


public static void main(String[] args) {


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

for(int i=0; i<5; i++) list.add(i);

Iterator<Integer> iterator = list.iterator();

//simple iteration

while(iterator.hasNext()){

int i = (int) iterator.next();

System.out.print(i + ", ");

}

System.out.println("\n"+list);

//modification of list using iterator

iterator = list.iterator();

while(iterator.hasNext()){

int x = (int) iterator.next();

if(x%2 ==0) iterator.remove();

}

System.out.println(list);

//changing list structure while iterating

iterator = list.iterator();

while(iterator.hasNext()){

int x = (int) iterator.next(); //ConcurrentModificationException here

if(x==1) list.add(10);

}

}

}

Comments

Popular posts from this blog

Jenkins CICD in One Page

Why do we need a build tool?

Deutsche Bank Interview Questions - 2024