简体   繁体   English

Java-经过2次或更多次for循环后,将元素添加到新列表中

[英]Java - Adding elements to a new list after going through 2 or more for loops

So this code is just one I made quickly and is not my actual code but I am trying to add specific values from one list to another list after going through two for loops and a few if statements . 因此,这段代码只是我快速编写的代码,而不是我的实际代码,但是在经历两个for loops和一些if statements后,我试图将一个列表中的特定值添加到另一个列表中。

Example Code 范例程式码

List<Integer> intList = new ArrayList<>();
//example list [0, 20, 10, 9, 11, 7, 9, 14]

List<Integer> result = new ArrayList<>();
for (i=0; i < intList.size()-1; i++) {
    for (j=i+1; j < intList.size(); j++) {
        if (intList.get(j) > intList.get(i)) {
            result.add(intList.get(i));
        }
    }
}
system.out.println(result);

Expected Result 预期结果

[0, 9, 7, 9]

So in this case, I want to have just 4 values in my list, however since I am going through the list multiple times through the 2 for loops I end up getting multiple repeats of the same values being added to the list (something like [0,0,0,0,0,9,9,9,7,7,9] ). 因此,在这种情况下,我希望列表中仅包含4个值,但是由于我要遍历2次for loops多次访问列表,所以我最终将相同值的多个重复添加到列表中(类似于[0,0,0,0,0,9,9,9,7,7,9] )。 How do I fix this without removing repeated values, since using that would result in removing the second 9 from the list too. 如何解决此问题而不删除重复的值,因为使用该值也会导致从列表中删除第二个9。

In your example you are comparing the indices of the array. 在您的示例中,您正在比较数组的索引。 You want to compare the values of the array at the respective indices. 您要比较数组在各个索引处的值。

You only need one loop and you need to guard against an out of bounds by making sure i is not the last index. 您只需要一个循环,就需要通过确保i不是最后一个索引来防止越界。

for (int i=0; i < intList.size()-1; i++) {
    if (intList.get(i+1) > intList.get(i)) {
        result.add(intList.get(i));
}

if I Understood the problem statement you are comparing pair value ie 0, 20 for first iteration and 10, 9 for second one so you need to add break statement to avoid duplicates and increment i value for comaparing next pair value 如果我理解了问题陈述,则您正在比较对值,即第一次迭代为0、20,第二次迭代为10、9,因此您需要添加break语句以避免重复,并增加i值以适应下一个对值

   List<Integer> intList = new ArrayList<>();

    //example list [0, 20, 10, 9, 11, 7, 9, 14]

    List<Integer> result = new ArrayList<>();
    for (int i=0; i < intList.size()-1; i++) {

        for (int j=i+1; j < intList.size(); j++) {

            if (intList.get(j) > intList.get(i)) {
                result.add(intList.get(i));                 
                break;
            }
            i++;
        }
    }
    System.out.println(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM