java list code example

Example 1: how to create a list in java

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

class scratch{
    public static void main(String[] args) {
        List<Integer> aList = new ArrayList<>();
        List<Integer> lList = new LinkedList<>();
    }
}

Example 2: list in java

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
public class Main {
   public static void main(String[] args) {
      List<String> list = new ArrayList<String>();
      list.add("a");
      list.add("b");
      list.add("c");
      list.add("d");
      list.add("e");
      list.add("f");
      
      //On met la liste dans le désordre
      Collections.shuffle(list);
      System.out.println(list);
      
      //On la remet dans l'ordre
      Collections.sort(list);
      System.out.println(list);
      
      Collections.rotate(list, -1);
      System.out.println(list);
      
      //On récupère une sous-liste
      List<String> sub = list.subList(2, 5);
      System.out.println(sub);
      Collections.reverse(sub);
      System.out.println(sub);
      
      //On récupère un ListIterator
      ListIterator<String> it = list.listIterator();
      while(it.hasNext()){
         String str = it.next();
         if(str.equals("d"))
            it.set("z");
      }
      while(it.hasPrevious())
         System.out.print(it.previous());
      
   }
}

Example 3: java list to set

Set<Foo> foo = new HashSet<Foo>(myList);

Example 4: java api add

boolean add(E e)

Appends the specified element to the end of this list (optional operation).

Lists that support this operation may place limitations on what elements may be added to this list. In particular, some lists will refuse to add null elements, and others will impose restrictions on the type of elements that may be added. List classes should clearly specify in their documentation any restrictions on what elements may be added.

Specified by:
    add in interface Collection<E>
Parameters:
    e - element to be appended to this list
Returns:
    true (as specified by Collection.add(E))
Throws:
    UnsupportedOperationException - if the add operation is not supported by this list
    ClassCastException - if the class of the specified element prevents it from being added to this list
    NullPointerException - if the specified element is null and this list does not permit null elements
    IllegalArgumentException - if some property of this element prevents it from being added to this list

Example 5: java list

import java.util.*;
var list = new ArrayList<String>();
list.add("Hello World!");

Example 6: java list

import java.util.*;
var list = new ArrayList<Foo>();
list.add(new Foo());