Java 常用技巧

一些 Java 零碎代码片段

Posted by mingfer on May 27, 2019

数据过滤

去除 List 中的 null 元素

1
2
3
4
5
6
7
8
9
10
11
12
@Test
public void trimNull() {
    final List<String> strings = Arrays.asList("test", null, "2", "test3", null);

    // 串行的方式去除 null 元素
    Assert.assertEquals(3, strings.stream()
                        .filter(Objects::nonNull).collect(Collectors.toList()).size());

    // 并行的方式去除 null 元素,线程不安全
    Assert.assertEquals(3, strings.parallelStream()
                        .filter(Objects::nonNull).collect(Collectors.toList()).size());
}

异常处理

获取异常的 Root Cause

1
2
3
4
5
6
7
8
public static Throwable getRootCause(Throwable e) {
    Throwable cause = null; 
    Throwable result = e;
    while(null != (cause = result.getCause())  && (result != cause) ) {
        result = cause;
    }
    return result;
}