Here you can find the source of getUnique(Collection
Parameter | Description |
---|---|
collection | The collection of elements that is expected to be of size 1. |
Parameter | Description |
---|---|
IllegalStateException | If the collection size is different from 1. |
public static <T> T getUnique(Collection<T> collection)
//package com.java2s; /*/*from w ww . j a v a2s .com*/ * Entwined STM * * (c) Copyright 2013 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied * verbatim in the file "COPYING". In applying this licence, CERN does not waive the privileges and immunities granted * to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction. */ import java.util.Collection; public class Main { /** * Returns the only element in the given collection. * * @param collection The collection of elements that is expected to be of size 1. * @return The only element in the collection. * @throws IllegalStateException If the collection size is different from 1. */ public static <T> T getUnique(Collection<T> collection) { checkNull("Collection", collection); if (collection.size() != 1) { throw new IllegalArgumentException( "Collection " + collection + " is expected to contain only one element"); } return collection.iterator().next(); } /** * A facility method that checks object to be null and throws the {@link IllegalArgumentException} if it is. This * method can be chained as it returns the value in case of success. * * @param <T> Type of the checked and returned value. * @param name The object's name. * @param value The object. * @return The passed object. */ public static <T> T checkNull(String name, T value) { if (null == value) { throw new IllegalArgumentException(name + " can't be null"); } return value; } /** * A facility method that checks object to be null and throws the {@link IllegalArgumentException} if it is. This * method can be chained as it returns the value in case of success. * * @param name The object's name. * @param value The object. * @return The passed value string in case of success. */ public static String checkNull(String name, String value) { if (null == value) { throw new IllegalArgumentException(name + " can't be null"); } if (value.trim().length() == 0) { throw new IllegalArgumentException(name + " can't be empty or be constituted only of spaces"); } return value; } }