【问题标题】:Collection to Iterable集合到可迭代
【发布时间】:2012-04-02 04:57:21
【问题描述】:

如何从SetList 之类的集合中获取java.lang.Iterable? 谢谢!

【问题讨论】:

  • 您的意思是Iterator 而不是IterableList 实现了 Iterable 接口。 Iterator 允许您遍历 List 的元素。
  • 我的界面其实是SortedSet

标签: java collections iterable


【解决方案1】:
public static void main(String args[]) {
    List<String> list = new ArrayList<String>();
    list.add("a string");


    Collection<String> collection = list;
    Iterable<String> iterable = collections;
    for (String s : iterable) {
        System.out.println(s);
    }

list -> collection->iterable
}

【讨论】:

    【解决方案2】:

    CollectionIterable

    所以你可以写:

    public static void main(String args[]) {
        List<String> list = new ArrayList<String>();
        list.add("a string");
    
        Iterable<String> iterable = list;
        for (String s : iterable) {
            System.out.println(s);
        }
    }
    

    【讨论】:

    • 我知道 OP 询问过它,但分配给 Iterable 是完全没有必要的。
    • @nwinkler 同意你的评论。
    • 谢谢,这是一个普遍问题
    • @myborobudur:你对仿制药有什么问题?
    【解决方案3】:

    我不清楚你需要什么,所以:

    这会给你一个迭代器

    SortedSet<String> sortedSet = new TreeSet<String>();
    Iterator<String> iterator = sortedSet.iterator();
    

    Sets 和 Lists 是 Iterables,这就是为什么您可以执行以下操作:

    SortedSet<String> sortedSet = new TreeSet<String>();
    Iterable<String> iterable = (Iterable<String>)sortedSet;
    

    【讨论】:

    • OP 要求Iterable 而不是Iterator
    • 谢谢,这是一个普遍问题
    【解决方案4】:

    java.util.Collection 扩展 java.lang.Iterable,你不需要做任何事情,它已经是一个 Iterable。

    groovy:000> mylist = [1,2,3]
    ===> [1, 2, 3]
    groovy:000> mylist.class
    ===> class java.util.ArrayList
    groovy:000> mylist instanceof Iterable
    ===> true
    groovy:000> def doStuffWithIterable(Iterable i) {
    groovy:001>   def iterator = i.iterator()
    groovy:002>   while (iterator.hasNext()) {
    groovy:003>     println iterator.next()
    groovy:004>   }
    groovy:005> }
    ===> true
    groovy:000> doStuffWithIterable(mylist)
    1
    2
    3
    ===> null
    

    【讨论】:

      【解决方案5】:

      SetList 接口都扩展了 Collection 接口,后者本身扩展了 Iterable 接口。

      【讨论】:

      • 谢谢,这是一个普遍问题
      【解决方案6】:

      IterableCollection 的超接口,因此任何实现Collection 的类(例如SetList)也实现Iterable

      【讨论】:

      • 谢谢,这是一个普遍问题
      猜你喜欢
      • 2022-07-05
      • 1970-01-01
      • 2017-06-18
      • 2019-02-14
      • 2011-04-25
      • 1970-01-01
      • 1970-01-01
      • 2011-02-17
      • 2012-12-29
      相关资源
      最近更新 更多