【问题标题】:How to iterate by priority?如何按优先级迭代?
【发布时间】:2019-08-11 19:45:15
【问题描述】:

在 java 中,假设我有一个名为 ExampleClass 的类,它有一个名为 Item 的类的集合。每个项目在称为 ID 的字段中都有一个整数。如何让 ExampleClass 的迭代器遍历具有偶数 ID 的项目,然后遍历具有奇数 ID 的项目。

编辑:我不需要这个特定问题的答案,我一般问如何在 ExampleClass 中有一个迭代器内部类 这将首先遍历具有一个属性的项目,然后再遍历其他项目。

【问题讨论】:

  • items.stream().sorted(Comparator.comparingInt(i -> i.getID() % 2)).iterator()
  • @shmosel 太糟糕了,它不能被赞成或接受为答案,因为您将答案发布为评论......

标签: java iterator


【解决方案1】:

您可以使用以下 if 条件来检查 ID 是否为奇数:

for(int i = 0;i < maxID;i++) { //I'm not sure what your maximum ID is.
  if(Item.ID % 2 == 0) {
    //Iterate
  }
}

然后,您可以对奇数 ID 执行相同的操作:

for(int i = 0;i < maxID;i++) { //I'm not sure what your maximum ID is.
  if(Item.ID % 2 == 1) {
    //Iterate
  }
}

代码Item.ID % 2 将ID 除以2,然后返回余数。在 if 语句中,它检查余数是否为 0。如果是,则 ID 为偶数,并运行所需的代码。但是,如果余数为 1,则该数为奇数。

例如:4 / 2 = 2。余数为 0。因此,4 是偶数。

例如:5 / 2 = 2。余数为 1。因此,5 是奇数。

【讨论】:

    【解决方案2】:

    这里有两种方法可以让您使用 1 衬里。

    final Iterator<Item> it = items.stream().filter(i.getID() % 2 == 0).iterator();
    

    for (final Item i : items.stream().filter(i.getID() % 2 == 0).toArray())
         doSomethingWith(i);
    

    【讨论】:

      【解决方案3】:

      如果您需要以任何特定顺序遍历它们,则需要在遍历它们之前对项目数组进行排序。根据您的应用程序和订购需求,您将如何实现这一点取决于您。我建议一些类似于伪代码的东西:

      unsortedArray[]
      sortedArray[]
      
      for (every element in unsortedArray) {
          id = element.ID; //Or sort value calculated with some other method
          sortedIndexBeforeID = sortedArray.findLastElementWithIDBelow(id); //Get the index of sorted element with an ID just before ours.
          sortedArray.insert(element,sortedIDBeforeID); //Add the element into the sorted array at given index, pushing the rest of the elements around
      }
      
      sortedArray[]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多