Java: Get first item from a collection

后端 未结 12 1088
说谎
说谎 2020-11-29 17:08

If I have a collection, such as Collection strs, how can I get the first item out? I could just call an Iterator, take its first

相关标签:
12条回答
  • 2020-11-29 17:25

    In Java 8 you have some many operators to use, for instance limit

         /**
     * Operator that limit the total number of items emitted through the pipeline
     * Shall print
     * [1]
     * @throws InterruptedException
     */
    @Test
    public void limitStream() throws InterruptedException {
        List<Integer> list = Arrays.asList(1, 2, 3, 1, 4, 2, 3)
                                   .stream()
                                   .limit(1)
                                   .collect(toList());
        System.out.println(list);
    }
    
    0 讨论(0)
  • 2020-11-29 17:29

    If you know that the collection is a queue then you can cast the collection to a queue and get it easily.

    There are several structures you can use to get the order, but you will need to cast to it.

    0 讨论(0)
  • 2020-11-29 17:31

    Looks like that is the best way to do it:

    String first = strs.iterator().next();
    

    Great question... At first, it seems like an oversight for the Collection interface.

    Note that "first" won't always return the first thing you put in the collection, and may only make sense for ordered collections. Maybe that is why there isn't a get(item) call, since the order isn't necessarily preserved.

    While it might seem a bit wasteful, it might not be as bad as you think. The Iterator really just contains indexing information into the collection, not a usually a copy of the entire collection. Invoking this method does instantiate the Iterator object, but that is really the only overhead (not like copying all the elements).

    For example, looking at the type returned by the ArrayList<String>.iterator() method, we see that it is ArrayList::Itr. This is an internal class that just accesses the elements of the list directly, rather than copying them.

    Just be sure you check the return of iterator() since it may be empty or null depending on the implementation.

    0 讨论(0)
  • 2020-11-29 17:39

    Guava provides an onlyElement Collector, but only use it if you expect the collection to have exactly one element.

    Collection<String> stringCollection = ...;
    String string = collection.stream().collect(MoreCollectors.onlyElement())
    

    If you are unsure of how many elements there are, use findFirst.

    Optional<String> optionalString = collection.stream().findFirst();
    
    0 讨论(0)
  • 2020-11-29 17:40

    In java 8:

    Optional<String> firstElement = collection.stream().findFirst();
    

    For older versions of java, there is a getFirst method in Guava Iterables:

    Iterables.getFirst(iterable, defaultValue)
    
    0 讨论(0)
  • 2020-11-29 17:40

    Functional way:

    public static <T> Optional<T> findFirst(List<T> result) {
        return Optional.ofNullable(result)
                .map(List::stream)
                .flatMap(Stream::findFirst);
    }
    

    above code snippet preserve from NullPointerException and IndexOutOfBoundsException

    0 讨论(0)
提交回复
热议问题