Skip to content

Instantly share code, notes, and snippets.

@amelieykw
Last active July 16, 2018 22:33
Show Gist options
  • Save amelieykw/020c51f6958a424c03aa5e335f052099 to your computer and use it in GitHub Desktop.
Save amelieykw/020c51f6958a424c03aa5e335f052099 to your computer and use it in GitHub Desktop.
[Java - Get/Search in ArrayList] #Java #Get #Search #ArrayList #tutorial #interview
  • Get Sub List of ArrayList
  • Get the index of last occurrence of the element in the ArrayList
  • Get element from ArrayList
  • Get the index of first occurrence of the element in the ArrayList
  • Check whether element exists in ArrayList
List subList(int fromIndex, int toIndex)

Example:

package beginnersbook.com;
import java.util.ArrayList;
import java.util.List;
public class SublistExample {

 public static void main(String a[]){
     ArrayList<String> al = new ArrayList<String>();

     //Addition of elements in ArrayList
     al.add("Steve");
     al.add("Justin");
     al.add("Ajeet");
     al.add("John");
     al.add("Arnold");
     al.add("Chaitanya");

     System.out.println("Original ArrayList Content: "+al);

     //Sublist to ArrayList
     ArrayList<String> al2 = new ArrayList<String>(al.subList(1, 4));
     System.out.println("SubList stored in ArrayList: "+al2);

     //Sublist to List
     List<String> list = al.subList(1, 4);
     System.out.println("SubList stored in List: "+list);
  }
}

Output:

Original ArrayList Content: [Steve, Justin, Ajeet, John, Arnold, Chaitanya]
SubList stored in ArrayList: [Justin, Ajeet, John]
SubList stored in List: [Justin, Ajeet, John]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment