Returns the single element contained in a collection or a null if the collection is null or empty. - Java java.util

Java examples for java.util:Collection Null Element

Description

Returns the single element contained in a collection or a null if the collection is null or empty.

Demo Code


//package com.java2s;

import java.util.Collection;

import java.util.NoSuchElementException;

public class Main {
    public static void main(String[] argv) {
        Collection c = java.util.Arrays.asList("asdf", "java2s.com");
        System.out.println(getUniqueElement(c));
    }//from   w ww  . j  a v a2 s. c  om


    public static Object getUniqueElement(Collection c)
            throws NoSuchElementException {
        // Return null if list is null or empty
        if (c == null || c.isEmpty())
            return null;

        // Throw an exception if collection has more than one element
        if (c.size() > 1) {
            NoSuchElementException exc = new NoSuchElementException(
                    "CollectionHelper.getUniqueElement() called with a collection containing "
                            + "more than one element.");
            throw exc;
        }

        return c.iterator().next();
    }
}

Related Tutorials