Return Any element In a Collection - Java java.util

Java examples for java.util:Collection Element

Description

Return Any element In a Collection

Demo Code


//package com.java2s;
import java.util.Collection;
import java.util.Iterator;

import java.util.Optional;

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

    public static <T> Optional<T> findAnyIn(Collection<T> collection) {
        final Iterator<T> iterator = collection.iterator();
        if (iterator.hasNext()) {
            return Optional.of(iterator.next());
        }
        return Optional.empty();
    }
}

Related Tutorials