Java 如何按优先级进行迭代?
在java中,我有一个名为ExampleClass的类,它有一个名为Item的类集合。每个项在名为ID的字段中都有一个整数。如何让ExampleClass的迭代器遍历具有偶数ID的项,然后遍历具有奇数ID的项 编辑:我不需要这个特定问题的答案,我只是问如何在ExampleClass中有一个迭代器内部类Java 如何按优先级进行迭代?,java,iterator,Java,Iterator,在java中,我有一个名为ExampleClass的类,它有一个名为Item的类集合。每个项在名为ID的字段中都有一个整数。如何让ExampleClass的迭代器遍历具有偶数ID的项,然后遍历具有奇数ID的项 编辑:我不需要这个特定问题的答案,我只是问如何在ExampleClass中有一个迭代器内部类 这将首先遍历具有一个属性的项,然后遍历其他属性。您可以使用以下if条件检查ID是否为奇数: for(int i = 0;i < maxID;i++) { //I'm not sure wha
这将首先遍历具有一个属性的项,然后遍历其他属性。您可以使用以下if条件检查ID是否为奇数:
for(int i = 0;i < maxID;i++) { //I'm not sure what your maximum ID is.
if(Item.ID % 2 == 0) {
//Iterate
}
}
for(inti=0;i
然后,您可以对奇数ID执行相同的操作:
for(int i = 0;i < maxID;i++) { //I'm not sure what your maximum ID is.
if(Item.ID % 2 == 1) {
//Iterate
}
}
for(inti=0;i
代码Item.ID%2
将ID除以2,并返回余数。在if语句中,它检查余数是否为0。如果是,则ID为偶数,并运行所需的代码。但是,如果余数为1,则该数字为奇数
示例:4/2=2
。余数是0。因此,数字4
是偶数
示例:
5/2=2
。余数为1。因此,数字5
是奇数。您可以使用以下if条件检查ID是否为奇数:
for(int i = 0;i < maxID;i++) { //I'm not sure what your maximum ID is.
if(Item.ID % 2 == 0) {
//Iterate
}
}
for(inti=0;i
然后,您可以对奇数ID执行相同的操作:
for(int i = 0;i < maxID;i++) { //I'm not sure what your maximum ID is.
if(Item.ID % 2 == 1) {
//Iterate
}
}
for(inti=0;i
代码Item.ID%2
将ID除以2,并返回余数。在if语句中,它检查余数是否为0。如果是,则ID为偶数,并运行所需的代码。但是,如果余数为1,则该数字为奇数
示例:4/2=2
。余数是0。因此,数字4
是偶数
示例:
5/2=2
。余数为1。因此,数字5
是奇数。这里有两种方法可以使用1行程序来处理
final Iterator<Item> it = items.stream().filter(i.getID() % 2 == 0).iterator();
这里有两种方法,你可以用一行来完成
final Iterator<Item> it = items.stream().filter(i.getID() % 2 == 0).iterator();
如果您需要以任何特定的顺序遍历它们,那么在循环遍历它们之前,您需要对项目数组进行排序。根据您的应用程序和订购需求,您将决定如何进行这项工作。我建议做一些类似伪代码的事情:
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[]
如果您需要以任何特定的顺序遍历它们,那么在循环遍历它们之前,您需要对项目数组进行排序。根据您的应用程序和订购需求,您将决定如何进行这项工作。我建议做一些类似伪代码的事情:
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[]
items.stream(),既然你把答案贴成评论。。。