Created
January 16, 2019 08:00
-
-
Save alonWang/59d9f04ced7174d5e96c36b2d6b9bed6 to your computer and use it in GitHub Desktop.
map的lambda封装尝试
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MapUtil { | |
/** | |
* 如果map中存在key,将其转化后进行处理 | |
* | |
* @param map | |
* @param key | |
* @param mapper | |
* @param consumer | |
* @param <K> | |
* @param <V> | |
* @param <R> | |
*/ | |
public static <K, V, R> void proceedIfPresent(Map<K, V> map, K key, | |
Function<V, R> mapper, Consumer<R> consumer) { | |
if (CollectionUtils.isEmpty(map)) { | |
return; | |
} | |
V value = map.get(key); | |
if (value != null) { | |
R r = mapper.apply(value); | |
consumer.accept(r); | |
} | |
} | |
public static void main(String[] args) { | |
Map<String, String> map = new HashMap<>(); | |
map.put("1", "1"); | |
// 打印1 | |
MapUtil.proceedIfPresent(map, "1", Integer::parseInt, | |
System.out::println); | |
// 无输出 | |
MapUtil.proceedIfPresent(map, "2", Integer::parseInt, | |
System.out::println); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment