如何在java中合并多个map的两个成员? [英] How to merge two members of a multimap in java?
本文介绍了如何在java中合并多个map的两个成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在java中编写了一个multimap,我想将这个map的两个成员相互合并。地图如下:
I have written a multimap in java and I want to merge two members of this map to each other. the map is as follow:
Map<Integer,Map<Integer,Integer>> groups = new HashMap<>();
例如,如果group [0]为0 => {0 = 1,1 = 10}且组[1]为1 => {0 = 2,1 = 3},我想答案是1 => {0 = 2,1 = 3,2 = 1,3 = 10}。我怎么能这样做?
我尝试了什么:
我搜索过它,但我找不到合适的解决方案
for example if group[0] is 0 => {0=1, 1=10} and group[1] is 1 => {0=2, 1=3}, I want the answer be 1 => {0=2, 1=3,2=1, 3=10}. how can I do this?
What I have tried:
I searched about it, but I could not find a proper solution
推荐答案
好吧,如果精彩的Java
库不提供直接的解决方案,那么,你知道,你可能会使用开发技术,如迭代,条件语句等......
Well, if the wonderfulJava
libraries don't provide a direct solution, then, you know, you might resort to use development techniques, like iterations, conditional statements and the like...
Set <Integer> s0 = m.get(0).keySet();
Set <Integer> s1 = m.get(1).keySet();
Iterator <Integer> it0 = s0.iterator();
Iterator <Integer> it1 = s1.iterator();
Integer n0 = null;
Integer n1 = null;
Map <Integer, Integer> rm = new HashMap<Integer, Integer>();
int count = 1;
while (true)
{
if ( n0 == null && it0.hasNext() )
n0 = m.get(0).get(it0.next());
if ( n1 == null && it1.hasNext() )
n1 = m.get(1).get(it1.next());
if ( n0 == null )
{
if (n1 == null)
break;
else
{
rm.put(count, n1);
n1 = null;
++count;
}
}
else
{// here n0 != null
if (n1 == null)
{
rm.put(count, n0);
n0 = null;
++count;
}
else
{
if ( n0 < n1 )
{
rm.put(count, n0);
n0 = null;
++count;
}
else
{
rm.put(count, n1);
n1 = null;
++count;
}
}
}
这篇关于如何在java中合并多个map的两个成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文