简体   繁体   中英

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 .

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] ). How do I fix this without removing repeated values, since using that would result in removing the second 9 from the list too.

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.

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

   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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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