我正在尝试对long列表进行排序,并验证数字是否从1开始连续排列。我想在java8 / streams中做所有事情
persistedDs = dataset.repartition(101).persist(StorageLevel.DISK_ONLY)
我正在尝试通过将所有语句合并为一两个来查看是否存在更优化的方法。
答案 0 :(得分:1)
我会用不同的小方法来做到这一点,而不是用一种方法来做所有事情:
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
}
}