0

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.

snow_white
  • 31
  • 7
  • 1
    Does this answer your question? [How to sort a List/ArrayList?](https://stackoverflow.com/questions/16252269/how-to-sort-a-list-arraylist) There are several examples with lambdas and method references. – Didier L Feb 01 '22 at 00:05
  • Also note [When to use LinkedList over ArrayList in Java?](https://stackoverflow.com/q/322715/525036) – `LinkedList` is certainly not your best choice if the plan is sorting it. – Didier L Feb 01 '22 at 00:07

2 Answers2

1

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

Amar Alte
  • 23
  • 1
  • 4
0
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

Leni
  • 653
  • 1
  • 6
  • 23
  • Both answers are overly complicated ways to do `Collections.sort(list)`. Moreover this one does not properly handle overflows. – Didier L Feb 01 '22 at 00:09
  • Agree, but the question says "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." (So the question implies it's looking for a stream + lambda solution) – Leni Feb 01 '22 at 19:08