开发者

How to sort ArrayList<Long> in decreasing order?

开发者 https://www.devze.com 2023-03-03 04:32 出处:网络
How to sort an ArrayList<Long> in Java in de开发者_开发百科creasing order?Here\'s one way for your list:

How to sort an ArrayList<Long> in Java in de开发者_开发百科creasing order?


Here's one way for your list:

list.sort(null);
Collections.reverse(list);

Or you could implement your own Comparator to sort on and eliminate the reverse step:

list.sort((o1, o2) -> o2.compareTo(o1));

Or even more simply use Collections.reverseOrder() since you're only reversing:

list.sort(Collections.reverseOrder());


Comparator<Long> comparator = Collections.reverseOrder();
Collections.sort(arrayList, comparator);


You can use the following code which is given below;

Collections.sort(list, Collections.reverseOrder());

or if you are going to use custom comparator you can use as it is given below

Collections.sort(list, Collections.reverseOrder(new CustomComparator());

Where CustomComparator is a comparator class that compares the object which is present in the list.


Java 8

well doing this in java 8 is so much fun and easier

Collections.sort(variants,(a,b)->a.compareTo(b));
Collections.reverse(variants);

Lambda expressions rock here!!!

in case you needed a more than one line logic for comparing a and b you could write it like this

Collections.sort(variants,(a,b)->{
    int result = a.compareTo(b);
    return result;
});


Sort normally and use Collections.reverse();


For lamdas where your long value is somewhere in an object I recommend using:

.sorted((o1, o2) -> Long.compare(o1.getLong(), o2.getLong()))

or even better:

.sorted(Comparator.comparingLong(MyObject::getLong))


Sort, then reverse.


By using Collections.sort() with a comparator that provides the decreasing order. See Javadoc for Collections.sort.


A more general approach to implement our own Comparator as below

Collections.sort(lst,new Comparator<Long>(){
                public int compare(Long o1, Long o2) {
                    return o2.compareTo(o1);
                }
            });


The following approach will sort the list in descending order and also handles the 'null' values, just in case if you have any null values then Collections.sort() will throw NullPointerException

      Collections.sort(list, new Comparator<Long>() {
          public int compare(Long o1, Long o2) {
                  return o1==null?Integer.MAX_VALUE:o2==null?Integer.MIN_VALUE:o2.compareTo(o1);

        }
    });


You can also sort an ArrayList with a TreeSet instead of a comparator. Here's an example from a question I had before for an integer array. I'm using "numbers" as a placeholder name for the ArrayList.


     import.java.util.*;
        class MyClass{
        public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        ArrayList<Integer> numbers = new ArrayList<Integer>(); 

        TreeSet<Integer> ts = new TreeSet<Integer>(numbers);
        numbers = new ArrayList<Integer>(ts);
        System.out.println("\nThe numbers in ascending order are:");
        for(int i=0; i<numbers.size(); i++)
        System.out.print(numbers.get(i).intValue()+" ");
        System.out.println("\nThe numbers in descending order are:");
        for(int i=numbers.size()-1; i>=0; i--)
        System.out.print(numbers.get(i).intValue()+" ");
    }
}


So, There is something I would like to bring up which I think is important and I think that you should consider. runtime and memory. Say you have a list and want to sort it, well you can, there is a built in sort or you could develop your own. Then you say, want to reverse the list. That is the answer which is listed above.

If you are creating that list though, it might be good to use a different datastructure to store it and then just dump it into an array.

Heaps do just this. You filter in data, and it will handle everything, then you can pop everything off of the object and it would be sorted.

Another option would be to understand how maps work. A lot of times, a Map or HashMap as something things are called, have an underlying concept behind it.

For example.... you feed in a bunch of key-value pairs where the key is the long, and when you add all the elements, you can do: .keys and it would return to you a sorted list automatically.

It depends on how you process the data prior as to how i think you should continue with your sorting and subsequent reverses


Comparator's comparing method can be used to compare the objects and then method reversed() can be applied to reverse the order -

list.stream().sorted(Comparator.comparing(Employee::getName).reversed()).collect(toList());


Using List.sort() and Comparator.comparingLong()

numberList.sort(Comparator.comparingLong(x -> -x));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号