Java: Get first item from a collection

后端 未结 12 1113
说谎
说谎 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 list = Arrays.asList(1, 2, 3, 1, 4, 2, 3)
                                   .stream()
                                   .limit(1)
                                   .collect(toList());
        System.out.println(list);
    }
    

提交回复
热议问题