Stream
处理集合类的遍历
toMap
Map<Long, User> userMap =
users.stream().collect(Collectors.toMap(User::getId, Function.identity()));
Map<Long, String> uidNameMap =
users.stream().collect(Collectors.toMap(User::getId, User::getName, (oldV, newV) -> newV));
toList
users.getList().stream().map(User::getId).collect(Collectors.toList());
foreach
map
filter
distinct
Optional
经常用于包装对象。
user对象为外部值,可能为空,这时候就可以使用
String nickName = Optional.ofNullable(user)
.map(user::getNickname)
.orElse(Constant.DEFAULT_NICK_NAME);
如果是要执行函数,那么使用orElseGet可以减少分支执行。
下面的代码中,如果user不为空,是不会执行函数的。但是如果直接用orElse会执行。
Optional.ofNullable(user).orElseGet(() -> createNewUser());
使用of也可以达到类似的效果。
Optional.of(id).ifPresent(t -> map.put("id", t));
抛异常:
User result = Optional.ofNullable(user)
.orElseThrow( () -> new IllegalArgumentException());
相关链接
3. CompletableFuture
可以更简单的使用并发
List<CompletableFuture<Optional<UserInfo>>> futures = Lists.newArrayList();
for (Long userId : uidIdList) {
futures.add(CompletableFuture.supplyAsync(() -> {
String key = RedisKey.getUserInfoKey(userId);
return cacheService.getObject(key, UserInfo.class);
}, ParallelQueryDcsExecutor.getExecutor()));
}
CompletableFuture<Void> allFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]));
try {
allFuture.get(PropProperties.getCacheQueryTimeOute(), TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException ex) {
throw new BizException(ErrorCodeEnum.CACHE_ERROR);
}
for (CompletableFuture<Optional<UserInfo>> future : futures) {
try {
future.get()
.ifPresent(userInfo -> cachedUserMap.put(userInfo.getUserID(), userInfo));
} catch (InterruptedException | ExecutionException ex) {
log.error("get userInfo error", ex);
}
}