Java List Null Empty listToItemOrNull(List list)

Here you can find the source of listToItemOrNull(List list)

Description

Transforms a list to a single item or to a null if the list has no item.

License

Open Source License

Parameter

Parameter Description
list the list to transform. May be <code>null</code>.

Return

the single list item or null.

Declaration

public static <T> T listToItemOrNull(List<T> list) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.List;

public class Main {
    /**//from   ww  w  . ja  v  a2  s.  com
     * Transforms a list to a single item or to a <code>null</code> if the list has no item.
     * <p>
     * Throws an {@link IllegalArgumentException} if the list has more than one item.
     *
     * @param list the list to transform. May be <code>null</code>.
     * @return the single list item or <code>null</code>.
     */
    public static <T> T listToItemOrNull(List<T> list) {
        if (list == null) {
            return null;
        } else {
            switch (list.size()) {
            case 0:
                return null;
            case 1:
                return list.get(0);
            default:
                throw new IllegalArgumentException("List has more than one item: " + list);
            }
        }
    }
}

Related

  1. isNullOrEmptyAwareEqual(final List targetOne, final List targetTwo)
  2. isNullOrEmptyList(final List list)
  3. isNullOrEmptyList(List list)
  4. isNullOrEmptyList(String message, List list)
  5. isObjectListEmpty(List list)
  6. listWithoutNull(A... elements)
  7. listWithoutNull(final List list)
  8. maskNull(List pTypes)
  9. newListIfNull(List list)