【问题标题】:Iterate through Collection<List<Integer>>遍历 Collection<List<Integer>>
【发布时间】:2013-12-18 09:33:13
【问题描述】:

我使用 Guava 库生成整数 123 的排列。

Collection<List<Integer>> vehCombinations = Collections2.orderedPermutations(vehicles);

接下来我需要遍历vehCombinations 并检查每个排列是否符合某些约束:

for (int j=0; j<vehCombinations.size(); j++)
{
  List<Integer> veh = vehCombinations.get(i);
}

vehCombinations.get(i) 是不允许的。

那么,如何从vehCombinations 中提取排列?

【问题讨论】:

  • "扰动:1) 焦虑;精神不安。2) 系统、运动物体或过程偏离其正常或正常的路径状态,由外部影响。”。 “排列:一种方式,尤其是几种可能的变体之一,其中可以对一组或多个事物进行排序或排列。”。你可能是指第二个:)

标签: java collections guava


【解决方案1】:

使用 foreach,如下所示:

for(List<Integer> veh : vehCombinations){
    veh.doSomething();
}

【讨论】:

    【解决方案2】:

    您可以使用 for each 语法:

    for(List<Integer> veh : vehCombinations) {
      // Do stuff
    }
    

    【讨论】:

      【解决方案3】:

      使用

      for(List<Integer> veh : vehCombinations){
         // write your logic
      }
      

      有时如果您需要编写自己的集合扩展。也许 如果您想在将元素添加到列表时添加特殊行为, 或者您想编写一个实际上由数据库支持的 Iterable 询问。 Guava 提供了许多实用程序来简化这些任务 为你,也为我们。

      看看这些东西

      Forwarding Decorators

      在那看看

      1.PeekingIterator

      List<E> result = Lists.newArrayList();
      PeekingIterator<E> iter = Iterators.peekingIterator(source.iterator());
      while (iter.hasNext()) {
        E current = iter.next();
        while (iter.hasNext() && iter.peek().equals(current)) {
          // skip this duplicate element
          iter.next();
        }
        result.add(current);
      }
      

      2.抽象迭代器

      public static Iterator<String> skipNulls(final Iterator<String> in) {
        return new AbstractIterator<String>() {
          protected String computeNext() {
            while (in.hasNext()) {
              String s = in.next();
              if (s != null) {
                return s;
              }
            }
            return endOfData();
          }
        };
      }
      

      3.AbstractSequentialIterator

       Iterator<Integer> powersOfTwo = new AbstractSequentialIterator<Integer>(1) { // note the initial value!
           protected Integer computeNext(Integer previous) {
             return (previous == 1 << 30) ? null : previous * 2;
           }
         };
      

      【讨论】:

        【解决方案4】:

        或者你可以使用迭代器:

        Iterator<List<Integer>> pageIterator = vehCombinations.iterator();
            while (pageIterator.hasNext()) {
                List<Integer> list = (List<Integer>) pageIterator.next();
            }
        

        【讨论】:

          猜你喜欢
          • 2015-10-03
          • 1970-01-01
          • 2012-06-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-08-15
          • 2015-06-17
          • 2013-10-26
          相关资源
          最近更新 更多