Home > Blockchain >  Move zeroes to end of Array List while keeping order of other numbers the same
Move zeroes to end of Array List while keeping order of other numbers the same

Time:10-30

I am having trouble moving all the zeroes in array list to the end of the array list while keeping the non zero numbers in the same order as they were. For example, lets say the array list has the numbers (0,1,0,3,12), the program should output (1,3,12,0,0). The problem with my output is that when I print the list, it prints it in the same way as the original list, I am confused on what I need to add to fix this.

My code:

List<Integer> nums =Arrays.asList(0,1,0,3,12);
int last = 0;
int hold = nums.get(last  );

for (int i = 0; i < nums.size(); i  ) {
    if (nums.get(i) == 0) {
        hold = nums.get(i);
    }
}

for (int i = last; i < nums.size(); i  ) {
    int hold1 = nums.get(i);
    hold1 = 0;
}

System.out.println(nums);

Update: sorry in advance for the code block, I put it in the quotes block and it still printed out without it.

CodePudding user response:

You could use a custom comparator for this as follows:

public class CustomComparator implements Comparator<Integer> {
    @Override
    public int compare(Integer o1, Integer o2) {
        if (o1 == 0) {
            return 1; // sets 0 as greater than o2 and thus it is located after o2
        } else if (o2 == 0) {
            return -1; // sets 0 as greater than o1 and thus it is located after o1
        } else {
            return 0; // sets that o1 and o2 are equal, actually keeping the order
        }
    }
}

You would use this comparator easily:

List<Integer> nums =Arrays.asList(0,1,0,3,12);
Collections.sort(nums, new CustomComparator());
System.out.println(nums);

You can read more about custom comparators here:

  •  Tags:  
  • java
  • Related