金额累加问题

使用Reduce进行累加操作,参考这里

1
2
3
List<BigDecimal> bdList = new ArrayList<>();
//populate list
BigDecimal result = bdList.stream().reduce(BigDecimal.ZERO, BigDecimal::add);

查找集合的最后一个元素

JAVA8的Stream只提供了FindFirst功能,没有FindLast功能,可以使用Reduce来实现查找最后一个元素的效果

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import java.util.*;
import java.util.stream.*;

public class GetLastEleFromCollection {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("aaa");
        list.add("idddd");
        list.add("bbbb");

        String lastElement = list.stream()
            .reduce((first, second) -> second)
            .orElse(null);
        System.out.println(lastElement);
    }
}
1
bbbb

比较两个时间是否是同一天

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import java.time.*;
import java.time.temporal.*;

public class CompareDay {
    public static void main(String[] args) {

        final LocalDateTime now = LocalDateTime.now();
        final LocalDateTime localDateTime = LocalDateTime.of(2019, 9, 29, 0, 0, 0);
        System.out.println(localDateTime.truncatedTo(ChronoUnit.DAYS).isEqual(now.truncatedTo(ChronoUnit.DAYS)));
    }
}
1
true

实现与Python的zip函数功能

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import java.util.*;
import java.util.function.*;

public class Zip {
    public static void main(String[] args) {

        List<List<Integer>> result = handle(Arrays.asList(1, 2, 3), Arrays.asList(4, 5, 6), (i, j) -> Arrays.asList(i, j));
        System.out.println(result);
    }

    public static <T, U, R> List<R> handle(List<T> list, List<U> list1, BiFunction<T, U, R> biFunction) {

        List<R> result = new ArrayList<>();
        for(int i = 0; i < list.size(); i ++) {
            result.add(biFunction.apply(list.get(i), list1.get(i)));
        }
        return result;
    }
}
1
[[1 (\, 4)] (\, [2 (\, 5)]) (\, [3 (\, 6)])]

多个Predicate链

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import java.util.*;
import java.util.stream.*;
import java.util.function.*;

public class MorePredicate {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);

        final Predicate<Integer> predicate = i -> i % 2 == 0;
        final Predicate<Integer> predicate1 = predicate.and(integer -> integer > 5);

        List<Integer> result = list.stream()
            .filter(predicate1)
            .collect(Collectors.toList());
        System.out.println(result);
    }
}
1
[6]