Home > Mobile >  Sorting a LinkedList with a lambda expression
Sorting a LinkedList with a lambda expression

Time:02-01

Hello. I want to sort a newly created LinkedList ascending, all elements of the list are crated randomly. My task is to sort them with a Comparator, but I am not allowed to write a class that implements Comparator, rather I should sort it by a lambda expression. This is my code so far:

public List<Integer> methodName(int length, int min, int max){
        LinkedList<Integer> intll = new LinkedList<>();
        for (int i =0; i<length;i  ){
            intll.add(ThreadLocalRandom.current().nextInt(min,max 1));
        //Sorting part 

So far I tried using the sort method from Collections and List, but could not help me further more with that. Thank you very much for helping me in advance.

CodePudding user response:

LinkedList<Integer> sortedIntll = intll.stream().sorted(Comparator.comparingInt(Integer::valueOf)).collect(Collectors.toCollection(LinkedList::new));

CodePudding user response:

import java.util.stream.Collectors;

public List<Integer> methodName(int length, int min, int max) {
        LinkedList<Integer> intll = new LinkedList<>();
        for (int i =0; i<length;i  )
            intll.add(ThreadLocalRandom.current().nextInt(min,max 1));

        return intll.stream().sorted((a, b) -> a - b).collect(Collectors.toList());
}

if you want to change the sort order, use b - a instead of a - b

  •  Tags:  
  • Related