Creating class Context to hold String
and Map
datatypes
class Context {
String userId;
Map<String, List<Integer>> map;
public Context(String s, List<Integer> list) {
userId = s;
map = new HashMap<>();
map.put(userId, list);
}
public void setValues(String s, List<Integer> list) {
map.put(s, list);
}
}
Now creating the Solution class which has List<Context>
public class Solution {
public static void main(String[] args) {
List<Integer> list;
// Context c1
list = new ArrayList<>(Arrays.asList(1, 2, 3));
Context c1 = new Context("dev", list);
list = new ArrayList<>(Arrays.asList(-1, -3));
c1.setValues("dev2", list);
list = new ArrayList<>(Arrays.asList(-6, -3));
c1.setValues("dev3", list);
// Context c2
list = new ArrayList<>(Arrays.asList(12, 15, 18));
Context c2 = new Context("macy", list);
list = new ArrayList<>(Arrays.asList(-12, -13));
c2.setValues("macy2", list);
list = new ArrayList<>(Arrays.asList(-8, -18));
c2.setValues("macy3", list);
// Context c3
list = new ArrayList<>(Arrays.asList(20, 30));
Context c3 = new Context("bob", list);
list = new ArrayList<>(Arrays.asList(-31, -32));
c3.setValues("bob2", list);
// Context List
List<Context> contextList = new ArrayList<>();
contextList.addAll(Arrays.asList(c1, c2, c3));
retrieveRecords(contextList);
}
private static void retrieveRecords(List<Context> contextList) {
// regular way of retrieving map values
for (Context c : contextList) {
System.out.println(c.map);
}
System.out.println();
// Retrieving only those records which has String key as userID
for (Context c : contextList) {
System.out.println(c.userId + "\t=>\t" + c.map.get(c.userId));
}
}
}
