Sorting a double value of an object within an arrayList

后端 未结 5 968
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-28 15:07

I\'m trying to sort my custom class chromosome by the value of their score attribute which is a double. These chromosomes are stored within an ArrayList. I know I have to us

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-28 15:28

    Since java 8 you can sort list of Double elements very simple.

    list.sort(Comparator.comparingDouble(Chromosome::getScore));
    

    or

    Collections.sort(list, omparator.comparingDouble(Chromosome::getScore));
    

    If you wanna get sorted list but you don't want to change your beginning list you can do it as following:

    List sortedList = list.stream()
         .sorted(Comparator.comparingDouble(A::getScore))
         .collect(Collectors.toList()); 
    

提交回复
热议问题