Click here to Skip to main content
15,892,253 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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<>();

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
Posted
Updated 10-Aug-17 22:08pm

1 solution

Well, if the wonderful Java libraries don't provide a direct solution, then, you know, you might resort to use development techniques, like iterations, conditional statements and the like...

Java
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;
      }
    }
  }
 
Share this answer
 
Comments
Member 11807654 11-Aug-17 10:41am    
thanks, but my map is a multimap.I found a solution but I do not know how to change it to work on a multimap. the solution was map.merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction) instruction(found in: http://farenda.com/java/java-util-map-merge-key-value-bifunction/). it sums the value of the members, but I do not want. I just want to merge the two members into one member of the map. how the remapping function can be written in my code?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900