Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using java8 how can we sort elements starting from the second element to till last?

Tags:

java-8

Using java8 how can we sort elements starting from the second element to till last?

  list.stream().filter(student -> student.getAge()!=15).sorted(Comparator.comparing(student->student.getAge())).collect(Collectors.toList());

The final sorted list should contain all the elements including first one.

I have tried above code snippet:

Here i dont want to touch first element.The above code is sorting from 2nd element to till last element.the problem is i am not getting first element(age =15) in output.

If i dont apply filter it will sort all the elements and i will loose first element, which should not happen.

Please help me on this.Thanks in advance.

like image 892
R.S Avatar asked Feb 05 '23 07:02

R.S


1 Answers

 List<Student> result = Stream.concat(
            list.stream().findFirst().map(Stream::of).orElse(Stream.empty()),
            list.stream().skip(1).sorted(Comparator.comparing(Student::getAge)))
            .collect(Collectors.toList());

    System.out.println(result);
like image 167
Eugene Avatar answered May 31 '23 23:05

Eugene