Reputation: 956
I am trying to sort a list of longs and validate if the numbers are in consecutive order starting from 1. I want to do everything in java8/streams
//sorting first
List<Long> sortedNums = request.stream().map(Request::getSequence)
.collect(Collectors.toList()).stream().sorted().collect(Collectors.toList());
//getting first num to see if the seq starting from 1
Optional<Long> first = sortedNums.stream().findFirst();
if (first.isPresent()) {
if (first.get() != 1) {
throw new BadRequestException("Sequence should start from 1");
}
}
//checking if the list is in consecutive order
if(!isConsecutive(sortedNums)) {
throw new BadRequestException("Sequences should be in consecutive order");
}
private boolean isConsecutive(List<Long> list) {
for (int i = 1; i < list.size(); i++) {
if (list.get(i - 1) + 1 != list.get(i)) {
return false;
}
}
return true;
}
I am trying to see if there is more optimal way of doing this with stream combining all the statements into one or two.
Upvotes: 1
Views: 1806
Reputation: 16498
I would do this in different small methods instead of one where you do everything:
public static boolean startsWith1(List<Long> list){
//return list.stream().sorted().findFirst().get() == 1; //see @Holger's comment
return Collections.min(list) == 1;
}
// The sum of all numbers from 1 to n = n * (n+1) /2;
// you can use that to check if your list contains all numbers from 1 to n
public static boolean isConsecutive(List<Long> list){
long n = list.size();
return list.stream().mapToLong(Long::longValue).distinct().sum() == n * (n+1) /2;
}
public static void doSomething(List<Long> list) throws BadRequestException{
if(!startsWith1(list)){
throw new BadRequestException("Sequence should start from 1 ");
}
if(!isConsecutive(list)) {
throw new BadRequestException("Sequences should be in consecutive order");
}
else{
// do whatever with your list
}
}
Upvotes: 1