AMZ DIGICOM

Digital Communication

AMZ DIGICOM

Digital Communication

Java List: methods and applications

PARTAGEZ

A List in Java is particularly suitable for scenarios in which the data volume size is not known beforehand or may change over time. We show you concrete examples of using lists, as well as the operations you can perform in combination.

What are lists used for in Java?

Lists are one of the basic data structures in Java programming and have a wide range of applications. They contain elements ordered that can be added, modified, deleted or extracted. Objects in a Java list can belong to multiple classes. It is also possible to save empty or duplicate elements. Additionally, Java lists are compatible with generic classes and methods, which ensures type safety.

Lists are for example applied in databases in which they are used to retain large volumes of data from database queries and access it. Java lists are often used in graphical user interfaces to display a list of items, for example the options in a drop-down menu or the individual items in an online store.

Java List is also indispensable in algorithms and data structures. It is used when implementingsorting algorithms, search algorithms, or queue and stack structures. In network applications, lists can help make associations and sockets easier to manage.

Java List methods

Java List is part of the Collections interface and must be imported from the package java.util. Implementation classes include Java ArrayList, LinkedList, Vector, and Stack. You can declare the different instances of the list as follows:

List linkedList = new LinkedList(); // LinkedList
List arrayList = new ArrayList(); // ArrayList
List vecList = new Vector(); // Vector
List stackList = new Stack(); //Stack

Java

Here are some of the most important methods used in connection with Java lists:

  1. int size(): determines the number of elements in a list.
  2. void add(int index, E element): adds an element at a specific position.
  3. boolean isEmpty(): checks that the list is empty.
  4. void clear(): removes all elements from the list.
  5. boolean contains(Object o): returns “true” if object “o” is present.
  6. boolean add(E e): adds the indicated element to the end of the list.
  7. boolean remove(Object o): removes the first instance of a specific element.
  8. E get(int index): returns the element to the indicated position.
  9. E set(int index, E element): replaces or inserts an element at the respective position.
  10. Object[] toArray(): returns an array with the elements of the list.
  11. List<E> subList(int fromIndex, int toIndex): Lists all items in the defined interval.
  12. default void replaceAll(UnaryOperator<E> operator): standard method in Java 8 which applies unary Java operators to each element and replaces the result with the corresponding element.

Typical applications of Java lists

Below we present the most common applications in a Java list. Among these are the conversions from arrays to lists and vice versa, as well as sorting, calling or modifying elements.

Convert an array to a list

To convert an array, you can run a list with loops and add the array elements in turn using the “.add()” method.

import java.util.*;

    public class ArrayToList{
      public static void main(String args[]){

      // Création d’un array
      String[] colors={"blue","green","red","yellow"};
      System.out.println("Array: "+Arrays.toString(colors));

      //Conversion de l’array en liste
      List<String> list=new ArrayList<String>();
      for(String color: colors){
        list.add(color);
      }
      System.out.println("List: "+list);
      }
    }

Java

The result is as follows:

Array: [blue, green, red, yellow]
List: [blue, green, red, yellow]

Java

Convert a list to an array

Using the “toArray()” method, a list can be transformed into an array:

import java.util.*;

    public class ListToArray{
      public static void main(String args[]){

       List<String> days = new ArrayList<String>();
       days.add("Monday");
       days.add("Tuesday");
       days.add("Wednesday");
       days.add("Thursday");
       days.add("Friday");
       days.add("Saturday");
       days.add("Sunday");

       // Conversion d’un ArrayList en array
       String[] array = days.toArray(new String[days.size()]);
       System.out.println("Array: "+Arrays.toString(array));
       System.out.println("List: "+days);
      }
    }

Java

In the result, we see that the contents of the array and that of the list are identical:

Array: [Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday]
List: [Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday]

Java

Calling elements of a Java List and modifying them

Using the “get()” method, you can access an element located at a specific position while with “set()”, an object can be replaced and added to the desired position.

import java.util.*;

    public class ListExample{
      public static void main(String args[]){

      // Création d’une liste
      List<String> letters=new ArrayList<String>();

      // Ajout d’éléments
      letters.add("a");
      letters.add("b");
      letters.add("c");

      // get()
      System.out.println("Element at index 1: "+letters.get(1));

      // set()
      letters.set(2, "d");

      for(String letter: letters)
      System.out.println(letter);
      }
    }

Java

The counting begins at position 0 in Java, the result obtained is therefore the following:

Element at index 1: b
a
b
d

Java

Sort a list

To sort a Java list, we can use the “.sort()” method of the Collections class. We iterate using a loop through the list, then pass the items to the screen one by one:

import java.util.*;

    class SortArrayList{
      public static void main(String args[]){

      // Création d’une liste de chiffres
      List<Integer> numbers=new ArrayList<Integer>();
      numbers.add(4);
      numbers.add(57);
      numbers.add(92);
      numbers.add(26);

      // Tri
      Collections.sort(numbers);

      for(Integer number: numbers)
        System.out.println(number);
      }
    }

Java

The numbers in the Java list are sorted in ascending order and thus displayed on the screen:

Télécharger notre livre blanc

Comment construire une stratégie de marketing digital ?

Le guide indispensable pour promouvoir votre marque en ligne

En savoir plus

Souhaitez vous Booster votre Business?

écrivez-nous et restez en contact