Here you can find the source of getSingleOrNull(Iterable
Parameter | Description |
---|---|
iterable | to find a single element. |
T | type of the element. |
Parameter | Description |
---|---|
IllegalStateException | in case the iterable contains more than 1 element. |
public static <T> T getSingleOrNull(Iterable<T> iterable)
//package com.java2s; /*/*from w w w . java 2s . c o m*/ * Copyright (c) [2011-2016] "Pivotal Software, Inc." / "Neo Technology" / "Graph Aware Ltd." * * This product is licensed to you under the Apache License, Version 2.0 (the "License"). * You may not use this product except in compliance with the License. * * This product may include a number of subcomponents with * separate copyright notices and license terms. Your use of the source * code for these subcomponents is subject to the terms and * conditions of the subcomponent's license, as noted in the LICENSE file. * */ import java.util.Iterator; public class Main { /** * Get a single element from iterator. * * @param iterator to find a single element. * @param <T> type of the element. * @return the element iff there is exactly one, null iff there is 0. * @throws IllegalStateException in case the iterable contains more than 1 element. */ public static <T> T getSingleOrNull(Iterator<T> iterator) { T result = null; if (iterator.hasNext()) { result = iterator.next(); } if (iterator.hasNext()) { throw new IllegalStateException("Iterable has more than one element, which is unexpected"); } return result; } /** * Get a single element from iterable. * * @param iterable to find a single element. * @param <T> type of the element. * @return the element iff there is exactly one, null iff there is 0. * @throws IllegalStateException in case the iterable contains more than 1 element. */ public static <T> T getSingleOrNull(Iterable<T> iterable) { return getSingleOrNull(iterable.iterator()); } }