Reputation: 41
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.
Upvotes: 4
Views: 743
Reputation: 298143
Rethink whether the Stream API is the best choice here:
List<Student> result = new ArrayList<>(list);
result.subList(1, list.size()).sort(Comparator.comparing(Student::getAge));
Note that if the source list is mutable and you don’t need the original list order, you can do the operation directly on the source list using only the second line of above code snippet.
Upvotes: 2
Reputation: 120848
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);
Upvotes: 4
Reputation: 34460
You could use List.subList
method to 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());
Upvotes: 2
Reputation: 16224
Try this, you can filter the first element after procesing the whole list:
Stream.concat(
Stream.of(list.stream().findFirst().get()),
list.stream().skip(1).sorted(Comparator.comparing(Student::getAge)))
.collect(Collectors.toList()).skip(1);
Upvotes: 0