Java hashMap合并算法

Python012

Java hashMap合并算法,第1张

用Kotlin语言写了一下,Java只要把MutableMap改成Map就可以了

import kotlin.random.Random

fun main(arg:Array<String>){

println("Hello World")

val map:Map<String, String> = hashMapOf(

"1242" to "A31_001", "2424" to "A31_001",

"3646" to "A31_002")

println("原map:$map")

val groups:HashMap<String, MutableMap<String, String>> = hashMapOf()

for((k, v) in map.entries){

if(!groups.containsKey(v)) groups.put(v, hashMapOf())

val m=groups.getValue(v)

m.put(k, v)

}

println("重组新map:$groups")

//给换成新随机id, 没必要但为满足要求

val newMap:HashMap<Int, MutableMap<String, String>> = hashMapOf()

var id:Int

for(v in groups.values){

do{ id=Random.nextInt()}

while(newMap.containsKey(id))

newMap.put(id,v)

}

println("新随机生成ID:$newMap")

}

> Task :run

Hello World

原map:{1242=A31_001, 3646=A31_002, 2424=A31_001}

重组新map:{A31_002={3646=A31_002}, A31_001={2424=A31_001, 1242=A31_001}}

新随机生成ID:{-91779881={2424=A31_001, 1242=A31_001}, 2102779363={3646=A31_002}}

BUILD SUCCESSFUL in 0s

package cn.utilsimport java.beans.BeanInfoimport java.beans.IntrospectionExceptionimport java.beans.Introspectorimport java.beans.PropertyDescriptorimport java.lang.reflect.InvocationTargetExceptionimport java.sql.Timestampimport java.text.ParseExceptionimport java.text.SimpleDateFormatimport java.util.ArrayListimport java.util.Dateimport java.util.Iteratorimport java.util.Listimport java.util.Mapimport java.util.regex.Patternimport org.apache.commons.beanutils.BeanUtilspublic class ExtendObject {/*** 将相同类型对象的内容向右合并* @param beanType 返回对象的类型* @param initObject 包含原始数据的对象* @param updateObject包含修改后数据的对象* @return返回两个对象的合并,相同属性的值如果convertedObject中包含,且不为null的话取它的值,否则取returnedObject的值*/@SuppressWarnings("unchecked")public Object extendObject(Object beanType, Object initObject, Object updateObject){Map map1 = BeanToMap(initObject)Map map2 = BeanToMap(updateObject)List list = getMapKeySet(map1)for(int i=0i<list.size()i++){Object map2Value = map2.get(list.get(i))if(null!=map2Value){map1.put(list.get(i), map2Value)}}return MapToBean(beanType, map1)}/*** 将map转化为bean* @param bean 将要转化成为的对象* @param map 被转化的map对象*/@SuppressWarnings("unchecked")public Object MapToBean(Object bean,Map map){Object type = nullDate date = null try {type = bean.getClass().newInstance()BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass())for(PropertyDescriptor p: beanInfo.getPropertyDescriptors()){String propertyName = p.getName()Object mapValue = map.get(propertyName)//去掉键为'class'的键值对if(null!=mapValue&&!"class".equals(propertyName)){//判断该字符转是否为日期类型if(CheckType.isDateType((String)mapValue)){String dateType = CheckType.getDateType((String)mapValue)if(dateType.equals("yyyy-MM-dd HH:mm:ss")){date = new SimpleDateFormat(dateType).parse((String)mapValue)p.getWriteMethod().invoke(type, new Timestamp(date.getTime()))}else{p.getWriteMethod().invoke(type, date)}//判断该字符串是否为整型,同时忽略值为数字,但是类型是字符串的Id们}else if(CheckType.isInt((String) mapValue)&&(!Pattern.matches("/w*Id", propertyName))){p.getWriteMethod().invoke(type, Integer.getInteger((String)mapValue).intValue())//默认剩下的类型都是字符串型}else{p.getWriteMethod().invoke(type, mapValue)}}}} catch (IntrospectionException e) {e.printStackTrace()} catch (InstantiationException e) {e.printStackTrace()} catch (IllegalAccessException e) {e.printStackTrace()} catch (IllegalArgumentException e) {e.printStackTrace()} catch (InvocationTargetException e) {e.printStackTrace()} catch (ParseException e) {e.printStackTrace()}return type}/*** 将bean转化为map* @param object* @return*/@SuppressWarnings("unchecked")public Map BeanToMap(Object object){Map map = null try {map = BeanUtils.describe(object)} catch (IllegalAccessException e) {e.printStackTrace()} catch (InvocationTargetException e) {e.printStackTrace()} catch (NoSuchMethodException e) {e.printStackTrace()}return map}/*** 获得对应Map的键值* @param map* @return*/@SuppressWarnings("unchecked")public List getMapKeySet(Map map){List list = new ArrayList()Iterator iterator = map.keySet().iterator()while(iterator.hasNext()){list.add(iterator.next())}return list}///**// * @param args// *///public static void main(String[] args) throws Exception{//System.out.println(isInt("1"))//Admin a = new Admin()//a.setAdminId("1")//a.setAdminPassword("1")////Admin b = new Admin()//b.setAdminPassword("2")//Admin c = (Admin)extendObject(new Admin(),a,b)//System.out.println(c.getAdminId()+"----"+c.getAdminPassword())//}}------------------------------------------------------------------------------------package cn.utilsimport java.util.regex.Patternpublic class CheckType {/*** 判断该字符串是否为日期类型* @param str* @return*/public static boolean isDateType(String str){Boolean b = falseString dateType1 ="/d{4}-/d{2}-/d{2}/s/d{2}:/d{2}:/d{2}./d*"String dateType2 ="/d{4}-/d{2}-/d{2}/s/d{2}:/d{2}:/d{2}"String dateType3 ="/d{4}-/d{2}-/d{2}"if(Pattern.matches(dateType1, str)||Pattern.matches(dateType2, str)||Pattern.matches(dateType3, str)){b = true}return b}/*** 返回字符串所属日期格式* @param str* @return*/public static String getDateType(String str){String dateType1 ="/d{4}-/d{2}-/d{2}/s/d{2}:/d{2}:/d{2}./d*"String dateType2 ="/d{4}-/d{2}-/d{2}/s/d{2}:/d{2}:/d{2}"String dateType3 ="/d{4}-/d{2}-/d{2}"if(Pattern.matches(dateType1, str)||Pattern.matches(dateType2, str)){return"yyyy-MM-dd HH:mm:ss"}if(Pattern.matches(dateType3, str)){return"yyyy-MM-dd"}return null}/*** 判断该字符串是否为整型* @param str* @return*/public static boolean isInt(String str){Boolean b = falseif(Pattern.matches("/d+", str)){b = true}return b}}

map的存储方式是一个key值对应一个value值 其中key值唯一,value值可以任意

collection存储的只是值,默认分配index号,和数组的index号类似

collection接口和map接口两个不同概念,存储数据的形式也不同,自然没关系

所以是C,D