'Maintain a transitive mapping in Java
Scenario
class A{
String aId;
;}
class B{
String bId;
;}
class C{
String bId;
;}
class D{
B b;
C c;
;}
I hava a List<A>. I traverse this list using a for loop, perform some DB operations and create a List<B>. I need a mapping from A to B, so I create a Map<A,B> also.
From this List<B>, I make a bulk API call and fetch a List<D>. I require a mapping from B to C also, so I traverse over this List<D> and create a Map<B,C> .
My main requirement is a mapping from A to C. I can't remove the bulk API call but want to remove the extra overhead of maintaining two maps. Is there some way of maintaining a transitive mapping, a mapping of A to C directly in JAVA?
Solution 1:[1]
You can generate it as follows:
for loop
import java.util.HashMap;
import java.util.Map;
public class Main
{
public static void main(String[] args)
{
Map<String,String> m1= new HashMap<>();
Map<String,String> m2 = new HashMap<>();
m1.put("aaa", "bbb");
m2.put("bbb", "ccc");
Map<String,String> combined = new HashMap<>();
for(String key : m1.keySet())
{
// TODO: add error handling or make sure get never returns null
combined.put(key, m2.get(m1.get(key)));
}
System.out.println(combined.get("aaa"));
}
}
streams
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;;
public class Main
{
public static void main(String[] args)
{
Map<String,String> m1= new HashMap<>();
Map<String,String> m2 = new HashMap<>();
m1.put("aaa", "bbb");
m2.put("bbb", "ccc");
Map<String,String> combined = m1.keySet().stream().collect(Collectors.toMap( Function.identity(), x->m2.get(m1.get(x))));
System.out.println(combined);
}
}
Edit: As requested, added a version using streams, even though I prefer the first version.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
