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

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

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

The last sorted list should contain all the elements, including the first.

I tried the code snippet:

Here I do not want to touch the first element. The above code is sorted from the second element to the last element. The problem is that I am not getting the first element (age = 15) in the output.

If I do not apply a filter, it sorts all the elements, and I lose the first element, which should not be.

Please help me with this. Thanks in advance.

+4
source share
4 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);
+4
source

You can use List.subListto skip the first element of the list:

List<Student> result = list.isEmpty() ? new ArrayList<>() : // or just list
    Stream.concat(
        Stream.of(list.get(0)),
        list.subList(1, list.size()).stream()
            .sorted(Comparator.comparing(Student::getAge)))
    .collect(Collectors.toList());
+2

, Stream API :

List<Student> result = new ArrayList<>(list);
result.subList(1, list.size()).sort(Comparator.comparing(Student::getAge));

Please note: if the original list is changed and you do not need the original order of the list, you can perform the operation directly in the original list using only the second line above the code fragment.

+2
source

Try this, you can filter the first element after processing the entire list:

Stream.concat(
        Stream.of(list.stream().findFirst().get()),
        list.stream().skip(1).sorted(Comparator.comparing(Student::getAge)))
        .collect(Collectors.toList()).skip(1);
0
source

Source: https://habr.com/ru/post/1678888/


All Articles