List In Java

List Interface is Used to store ordered values. duplicate value can be stored. it is a child interface of collection.

1. Adding Elements


public class Program1 {
    public static void main(String[] args) {
        /* List  can not be instantiated */
        // List<Integer> l1 = new List<Integer>();       
        List<Integer> l1 = new ArrayList<Integer>(); 
        /* it will not override value it shifts value if any present on that index */
        l1.add(0, 1);
        l1.add(0,2); 
        l1.add(0,22); 

        System.out.println(l1); // [22, 2, 1]

        List<Integer> l2 = new ArrayList<Integer>(); 
        l2.add(1);
        l2.add(11);
        l2.add(1111);
        System.out.println(l2); // [1, 11, 1111]

        /* put l1 values in 0 index other values will shilft */
        l2.addAll(0, l1);  
        System.out.println(l2); //  [22, 2, 1, 1, 11, 1111]

    }

}

2. remove , replace , and get element

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

// updating and remove and get  element
public class Program2 {
    public static void main(String[] args) {

        List<Integer> l1 = new ArrayList<Integer>(); 
        l1.add(1);
        l1.add(11);
        l1.add(1111);
        l1.add(1111);
        l1.add(1111);

        // set item at 0th index 
        l1.set(0, 23);
        System.out.println(l1);   //[23, 11, 1111, 1111, 1111]

        // get item 
        System.out.println(l1.get(2)); // 1111


        // remove item 
        l1.remove(0);
        l1.remove(0);
        System.out.println(l1); // [1111, 1111, 1111]

        List<String> l2 = new ArrayList<String>(); 
        l2.add("hello");
        l2.add("world");
        l2.add("edr");
        l2.add("ght");
        System.out.println(l2); // [hello, world, edr, ght]
        l2.remove("hello");  // remove object
        System.out.println(l2); //[world, edr, ght]

    }    
}

3. Iterating over List

/* iterating over list */ 
import java.util.List;
import java.util.ArrayList;

public class Program3 {
    public static void main(String[] args) {
        List<Integer> l1 = new ArrayList<>();

        l1.add(2);
        l1.add(23);
        l1.add(1, 900);
        /* using get method */ 
        for (int i = 0; i < l1.size(); i++) {
            System.out.print(l1.get(i) + " "); /* 2 900 23  */
         }   

        System.out.println(" \n" );
        /* using foreach */ 
        for (Integer i : l1) {
            System.out.println(" " + i);  /* 2 , 900 ,23 */
        }
    }
}

Did you find this article valuable?

Support Sanjay Prajapat's Blog by becoming a sponsor. Any amount is appreciated!