Java List

In Java List is an interface representing an ordered collection (also known as a sequence).

As an interface you cannot directly instantiate List<E>, instead it is there to be implemented by classes, which may then be instantiated.

And infact many important classes like the ArrayList either directly or indirectly implement this interface.

Then those implementers get precise control over which position an element is inserted. Afterwards you can access elements by their integer index (position in the list), and also search for elements in the list.

Lists can allow duplicate elements. If you don't want duplicates then it is recommended you use Set.

The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator, add, remove, equals, and hashCode methods. Declarations for other inherited methods are also included here for convenience.

The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.

The List interface provides a special iterator, called a ListIterator, that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.

The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches.

The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list.

List API Definition

List is an interface that itself implements the Collection<E> interface.

public interface List implements Collection<E>

Classes Implementing the List Interface.

Here are the classes that implement the List interface:

  1. AbstractList
  2. AbstractSequentialList
  3. ArrayList
  4. CopyOnWriteArrayList
  5. LinkedList
  6. ObservableArrayList
  7. ObservableList
  8. Stack
  9. Vector

The contains() method

private boolean isAdminRole(List<String> roles) {
    if (roles.contains("ROLE_ADMIN")) {
        return true;
    return false;

Here's second example:

public void convert(JSONObject temp){

        ArrayList<String> keySet = AdditionalFunc.getKeySet(temp.keys());

        try {

                code = (String) temp.get("code");
                ingredient = (String) temp.get("ingredient");
                classification = (String) temp.get("classification");
                url = (String) temp.get("url");
                usageCapacity = (String) temp.get("usage_capacity");

        }catch (Exception e){


The toArray() method

public Action[] getActions(boolean context) {
    List<? extends Action> actionsForPath = Utilities.actionsForPath("Android/ADB/EmulatorDevice");
    return actionsForPath.toArray(new Action[actionsForPath.size()]);
public void fromList(List<Point3> lp) {
    Point3 ap[] = lp.toArray(new Point3[0]);

List Examples:

(a). How to Remove Specific Item From a List via the contains()

In this first instance we will search a List using the contains() method and remove that item if found.

Our method will receive a List of strings and a search term

    private static void removeItemFromList(List<String> list,String itemToRemove) {
        System.out.println("list: " + list);
        try {
            for (String e : list) {
                if (list.contains(itemToRemove)) {
                    System.out.println("Calling list.remove(Two)...");
        } catch (Exception ex) {
        System.out.println("list: " + list);
(b). How to Search and Remove Specific Item From a List by Iterating

We will receive a List of strings and item to remove and iterate through the list via iterator and remove that item.

private static void removeItemViaIteration(List<String> list,String itemToRemove) {
    System.out.println("list: " + list);
    try {
        Iterator iter = list.iterator();
        while (iter.hasNext()) {
            String e = (String);
            if (itemToRemove.equals(e)) {
                System.out.println("Calling iter.remove()...");
    } catch (Exception ex) {
    System.out.println("list: " + list);
(c). How to Populate a Java List From SQL database

Say we have employee objects, first we will initialize the List<Rmp> to an arraylist.

Then open a connection to our database, then execure our SQL statement via the executeQuery() method thus returning a ResultSet.

We will then loop through thar resultset and get the properties of that employee, instantiate the Employee and add that employee to our List, before closing our database connection and returning that list.

public List<Emp> getEmpList() throws SQLException

    List<Emp> empList = new ArrayList<>();
    DBHelper db = DBHelper.getInstance();
    Connection conn = db.getConnection();
    ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM emp");

    Emp emp = null;
        int empno = rs.getInt("empno");
        String name = rs.getString(2);
        String job = rs.getString(3);
        int mgr = rs.getInt(4);
        String hiredate = rs.getString(5);
        double sal = rs.getDouble(6);
        double comm = rs.getDouble(7);
        int deptno = rs.getInt("deptno");
        empList.add(new Emp(empno, name, job, mgr, hiredate, sal, comm, deptno));
    return empList;
(d) Sample code for Filtering a List in Android
private final class WordFilter extends Filter {

            private final List<String> mItems;

            private WordFilter(List<String> items) {
                mItems = new ArrayList<>(items);

            protected FilterResults performFiltering(CharSequence constraint) {
                final List<String> list;

                if (TextUtils.isEmpty(constraint)) {
                    list = mItems;
                } else {
                    list = new ArrayList<>();
                    final String normalizedConstraint = Normalizer.forSearch(constraint);
                    for (String item : mItems) {
                        final String normalizedItem = Normalizer.forSearch(item);
                        if (normalizedItem.startsWith(normalizedConstraint) || //
                                normalizedItem.contains(" " + normalizedConstraint)) {

                final FilterResults results = new FilterResults();
                results.values = list;
                results.count = list.size();
                return results;

            protected void publishResults(CharSequence constraint, FilterResults results) {
                //noinspection unchecked
                mCheeses = (List<String>) results.values;
                mQuery = constraint != null ? constraint.toString() : null;
How To Remove Duplicates From an ArrayList using contains() method
private List<ACL> removeDuplicates(List<ACL> acl) {

        ArrayList<ACL> retval = new ArrayList<ACL>();
        Iterator<ACL> it = acl.iterator();
        while (it.hasNext()) {
            ACL a =;
            if (retval.contains(a) == false) {
        return retval;
How to Add an Item at the beginning of a List(Implementation)

Let's create a custom method that can add for us an object at the beginning of a List. You pass us the list as well as the object to add.

    public static void addToFirst(List list, Object object) {
        Object[] objects = list.toArray();
        for (int i = 0; i < objects.length; i++) {

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:


What do You Think

Dear readers drop us your comments below. We are building a community of students and learners. Start by dropping us your suggestions below. What tutorials do you want us to do for example? Where can we improve? What are some awesome resources out there? Do you have any code you want to share with us?
By the way that example or snippet you have lying in your computer can really help beginner programmers. We can share it here with other students.

Previous Post Next Post