抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >
1
2
3
4
5
6
7
8
9
10
11
12
13
// 创建一个Map
Map<String, Object> infoMap = new HashMap<>();
infoMap.put("name", "Zebe");
infoMap.put("site", "www.zebe.me");
infoMap.put("email", "zebe@vip.qq.com");
// 传统的Map迭代方式
for (Map.Entry<String, Object> entry : infoMap.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
// JDK8的迭代方式
infoMap.forEach((key, value) -> {
System.out.println(key + ":" + value);
});

看起来更屌的

1
2
3
4
5
6
7
8
9
10
11
12
13
public static String createToken(Map<String, String> claims) throws Exception {
try {
Algorithm algorithm = Algorithm.HMAC256(SECRET);
JWTCreator.Builder builder = JWT.create()
.withIssuer(ISSUER)
//设置过期时间为2小时
.withExpiresAt(DateUtils.addHours(new Date(), 2));
claims.forEach(builder::withClaim);
return builder.sign(algorithm);
} catch (IllegalArgumentException e) {
throw new Exception("生成token失败");
}
}

当然,java.util.Map 的 forEach 接收一个函数式接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
default void forEach(BiConsumer<? super K, ? super V> action) {
Objects.requireNonNull(action);
for (Map.Entry<K, V> entry : entrySet()) {
K k;
V v;
try {
k = entry.getKey();
v = entry.getValue();
} catch(IllegalStateException ise) {
// this usually means the entry is no longer in the map.
throw new ConcurrentModificationException(ise);
}
action.accept(k, v);
}
}

@FunctionalInterface
public interface BiConsumer<T, U> {
void accept(T t, U u);

default BiConsumer<T, U> andThen(BiConsumer<? super T, ? super U> after) {
Objects.requireNonNull(after);

return (l, r) -> {
accept(l, r);
after.accept(l, r);
};
}
}

BiConsumer 是一个函数式接口,它要求函数接收 2 个参数,看起来下面这个符合接口要求。

1
public Builder withClaim(String name, String value)

参考

Java8 - Map更优雅的迭代方式:forEach

java8新特性-foreach&lambda

评论