首页 文章

Java:从集合中获取第一个项目

提问于
浏览
235

如果我有一个集合,例如 Collection<String> strs ,我怎样才能获得第一个项目?我可以调用 Iterator ,取其第一个 next() ,然后抛出 Iterator . 有没有浪费的方法吗?

11 回答

  • 114

    Iterables.get(yourC, indexYouWant)

    因为,如果您正在使用收藏集,那么您应该使用Google收藏集 .

  • 377

    看起来这是最好的方法:

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

    很好的问题......起初,它似乎是对 Collection 界面的疏忽 .

    请注意"first"赢了'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 get(item) 调用,因为订单不一定保留 .

    虽然看起来有点浪费,但可能没有您想象的那么糟糕 . Iterator 实际上只包含集合中的索引信息,而不是通常是整个集合的副本 . 调用此方法会实例化 Iterator 对象,但这确实是唯一的开销(而不是复制所有元素) .

    例如,查看 ArrayList<String>.iterator() 方法返回的类型,我们看到它是 ArrayList::Itr . 这是一个内部类,它只是直接访问列表的元素,而不是复制它们 .

    请确保检查 iterator() 的返回,因为它可能为空或 null ,具体取决于实现 .

  • 0

    在java 8中:

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

    对于旧版本的java,在Guava _2589679中有一个getFirst方法:

    Iterables.getFirst(iterable, defaultValue)
    
  • 38

    Collection 中没有"first"项目,因为它只是一个集合 .

    从Java doc的Collection.iterator()方法:

    无法保证元素的退回顺序......

    所以你不能 .

    如果使用 anotheranother 接口,则可以执行以下操作:

    String first = strs.get(0);
    

    但直接来自Collection,这是不可能的 .

  • -2

    听起来你的收藏品想要像列表一样,所以我建议:

    List<String> myList = new ArrayList<String>();
    ...
    String first = myList.get(0);
    
  • 0

    在Java 8中,您可以使用许多运算符,例如 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);
    }
    
  • 4

    你可以做一个演员 . 例如,如果存在一个具有此定义的方法,并且您知道此方法返回List:

    Collection<String> getStrings();
    

    在调用它之后,你需要第一个元素,你可以这样做:

    List<String> listString = (List) getStrings();
    String firstElement = (listString.isEmpty() ? null : listString.get(0));
    
  • 1

    如果您知道该集合是一个队列,那么您可以将该集合转换为队列并轻松获取它 .

    您可以使用几种结构来获取订单,但您需要投射到它 .

  • 0

    它完全取决于您使用的实现,无论是arraylist链表还是其他set实现 .

    如果设置了那么你可以直接获取第一个元素,它们可以在集合上进行特技循环,创建一个值为1的变量,并在该循环之后标记值为1时获取值 .

    如果它是list的实现,那么通过定义索引号很容易 .

  • 2

    Guava提供 onlyElement Collector ,但只有在您希望集合只有一个元素时才使用它 .

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

    如果您不确定有多少元素,请使用 findFirst .

    Optional<String> optionalString = collection.stream().findFirst();
    
  • 68

    你可以这样做:

    String strz[] = strs.toArray(String[strs.size()]);
    String theFirstOne = strz[0];
    

    Collection的javadoc给出了数组元素的以下警告:

    如果此集合对其迭代器返回的元素的顺序做出任何保证,则此方法必须以相同的顺序返回元素 .

相关问题