使用java 8语法进行开发

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);
		}
	}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值