工作中有遇到获取map中指定key的情况,一个一个指定获取效率低不说,代码看起来乱,现整理的方法,希望给大家点思路
获取Map中指定key值进行处理封装方法
- public class CollectUtil {
-
- public static void main(String[] args) {
- Map<String,Object> map = new HashMap<>();
- map.put("aa","11");
- map.put("premium","22");
- map.put("num","33");
- List<String> keys = Arrays.asList("aa","bb","dd");
- //System.out.println(getMapCollection(map,keys));
- System.out.println(getMapCollection(map,DemoEntity.class));
-
- }
-
- /**
- * 根据keys获取map中指定key存入新map
- * @param maps
- * @param keys
- * @return
- * @param
- * @param
- */
- public static <K, V> Map<K,V> getMapCollection(Map<K,V> maps, Iterable<K> keys){
- Map<K,V> filterMaps = new HashMap<>();
- if(maps != null && !maps.isEmpty() && keys != null){
- keys.forEach(key -> Optional.ofNullable(maps.get(key)).ifPresent(value -> filterMaps.put(key,value)));
- }
- return filterMaps;
- }
-
- /**
- * 根据clazz实体类中属性获取map中对应key,存入新map
- * @param maps
- * @param clazz
- * @return
- * @param
- * @param
- */
- public static <K, V> Map<K,V> getMapCollection(Map<K,V> maps, Class<?> clazz){
- Map<K,V> filterMaps = new HashMap<>();
- Field[] fields = clazz.getDeclaredFields();
- if(maps != null && !maps.isEmpty() && fields != null){
- Arrays.stream(fields).forEach(field -> {
- String key = field.getName();
- Optional.ofNullable(maps.get(key)).ifPresent(value -> filterMaps.put((K)key, (V) value));
- });
- }
- return filterMaps;
- }
-
- /**
- * 根据keys获取map中指定key的值存如list
- * @param map
- * @param keys
- * @return
- * @param
- * @param
- */
- public static <K, V> List<V> getListCollection(Map<K, V> map, Iterable<K> keys) {
- List<V> result = new ArrayList<>();
- if (map != null && !map.isEmpty() && keys != null) {
- keys.forEach(key -> Optional.ofNullable(map.get(key)).ifPresent(result::add));
- }
- return result;
- }
-
- public static <K, V> List<V> getOrderCollection(Map<K, V> map, Iterable<K> keys, Comparator<V> comparator) {
- Objects.requireNonNull(comparator);
- List<V> result = getListCollection(map, keys);
- Collections.sort(result, comparator);
- return result;
- }
- }
-
- @Data
- public class DemoEntity {
-
- private int id;
- private Long premium;
- private String num;
- }