javaarrayssortingjava-8comparator

How to move a specific value to the end of the array without affecting the order of other elements?


Suppose I have an array of [0,7,4,0,0,8,3,0,0,0,5,6] and I have to take all the zeroes to last positions after other numbers without modifying their order. So the output array should be like : [7,4,8,3,5,6,0,0,0,0,0];

How will i get the desired result output using Java 8 , can anyone please suggest

I have tried using the following code

public class ZeroLast {

    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(0,7,4,0,0,8,3,0,0,0,5,6);
        list.sort(Comparator.reverseOrder());
        System.out.println(list);
    }
}

And the output is : [8, 7, 6, 5, 4, 3, 0, 0, 0, 0, 0, 0]

And i know this is because using reverseOrder() mthod it will sort the elements using Descending order and this is not the desired output what it should be . so anything i will do here to get the output or can you please give sample code logic part to get the results and Thanks.


Solution

  • you can use sort method on your list with a custom comparator to do it.

    List<Integer> list = Arrays.asList(0,7,4,0,0,8,3,0,0,0,5,6);
    list.sort((o1, o2) -> o1 == 0 ? 1 : (o2 == 0 ? -1 : 0));
    System.out.println(list);
    

    Using this all 0s must be at the end of the List without modifying any other order.