實用Java程式碼
阿新 • • 發佈:2018-11-16
一些實用的Java程式碼
往Map<Key,Collection>這種結構資料中插入值
public static <K, V, C> void setMapOfCollectionValue(Map<K,C> map,K key, V value, Class collectonClass){ if(map.containsKey(key)){ ((Collection)map.get(key)).add(value); }else{ try { Collection collection = (Collection)collectonClass.newInstance(); collection.add(value); map.put(key, (C)collection); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } }
物件克隆
1)在類中implements Cloneable實現clone方法
2)先序列化物件再反序列化物件,implements Serializable, org.springframework.util.SerializationUtils,序列化工具kryo等
3)新建一個物件,然後將屬性拷貝到新物件上
org.springframework.cglib.beans.BeanCopier,org.springframework.beans.BeanUtils,org.apache.commons.beanutils.PropertyUtils
import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; @Slf4j public class BeanUtil { public static <T> T clone(T source){ T target = null; try { target = (T) source.getClass().newInstance(); } catch (InstantiationException|IllegalAccessException e) { log.error("object clone error",e); } BeanUtils.copyProperties(source, target); return target; } }
mongo查詢排序
mongo查詢出來的列表順序並不是按照in裡面的順序返回的
public static <T,R> List<T> sortEntityByIds(List<T> entities, List<R> ids, Function<T,R> idFunc){
if(CollectionUtils.isEmpty(entities)){
return entities;
}
Map<R,T> entitiesMap = new HashMap<>();
for (T entity : entities) {
entitiesMap.put(idFunc.apply(entity), entity);
}
List sortEntities = new ArrayList<>();
for (R id : ids) {
T entity = entitiesMap.get(id);
if(null!=entity){
sortEntities.add(entity);
}
}
return sortEntities;
}
List<User> users = userRepository.findByIds(userIds);
List<User> sortedUsers = sortEnityByIds(users, userIds, User::getId);