Java examples for java.util:Collection Element
Gets one element from the provided Collection.
//package com.java2s; import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; public class Main { public static void main(String[] argv) { Collection collection = java.util.Arrays.asList("asdf", "java2s.com"); System.out.println(getAnyFrom(collection)); }//from w w w . j a v a 2 s . co m /** * Gets one element from the provided Collection. If no element is present, * an Exception is thrown. No guarantee is made as to which element is * returned from time to time. * * @param <T> Collection type * @param collection to use * @return one element from the provided Collection * @throws NoSuchElementException if no elements are present in the * Collection */ public static <T> T getAnyFrom(Collection<T> collection) { final Iterator<T> iterator = collection.iterator(); if (iterator.hasNext()) { return iterator.next(); } throw new NoSuchElementException("No value present"); } }