which data structure in java can hold hashmaps as its elements? - java

public static HashMap<String,Integer> users1 = new HashMap<>();
public static HashMap<String,Integer> users2 = new HashMap<>();
public static HashMap<String,Integer> users3 = new HashMap<>();
public static HashMap<String,Integer> users4 = new HashMap<>();
// Enter code here.
I need to add them into a arrayList or set or something and then they should be called when using that data structures index. Like is there any way to solve it

Or just simply use an array:
public static HashMap<String,Integer>[] users = HashMap<>[4];
users[0] = = new HashMap<>();
users[1] = = new HashMap<>();
users[2] = = new HashMap<>();
users[3] = = new HashMap<>();
And then use them:
users[0].add( "String", 123 );

you could as simply as :
List<HashMap<String, Integer>> list = new ArrayList<>();
// And then add them to list
list.add(users1);
list.add(users2);
...

ArrayList<HashMap> list = new ArrayList<>();
list.add(users1);

Related

How to list became parameter in method put?

I want to send data from the list as input to execute a stored procedure. In code below, all variable list which contains to be sent as an input parameter.
public void onClick$btnSend() throws Exception {
Workbook workbook = new Workbook("D:/excel file/Mapping Prod Matriks _Group Sales Commercial.xlsx");
com.aspose.cells.Worksheet worksheet = workbook.getWorksheets().get(0);
com.aspose.cells.Cells cells = worksheet.getCells();
Range displayRange = cells.getMaxDisplayRange();
List<String> ParaObjGroup = new ArrayList<String>();
List<String> ParaObjCode = new ArrayList<String>();
List<String> ParaProdMatrixId = new ArrayList<String>();
List<String> ParaProdChannelId = new ArrayList<String>();
List<String> ParaProdSalesGroupId = new ArrayList<String>();
List<String> ParaCustGroup = new ArrayList<String>();
List<String> ParaSlsThroughId = new ArrayList<String>();
List<Integer> Active = new ArrayList<Integer>();
for(int row= displayRange.getFirstRow()+1;row<displayRange.getRowCount();row++){
ParaObjGroup.add(displayRange.get(row,1).getStringValue());
ParaObjCode.add(displayRange.get(row,3).getStringValue());
ParaProdMatrixId.add(displayRange.get(row,5).getStringValue());
ParaProdChannelId.add(displayRange.get(row,7).getStringValue());
ParaProdSalesGroupId.add(displayRange.get(row,9).getStringValue());
ParaCustGroup.add(displayRange.get(row,11).getStringValue());
ParaSlsThroughId.add(displayRange.get(row,13).getStringValue());
Active.add(displayRange.get(row,14).getIntValue());
}
System.out.println(ParaObjGroup);
System.out.println(ParaObjCode);
System.out.println(ParaProdMatrixId);
System.out.println(ParaProdChannelId);
System.out.println(ParaProdSalesGroupId);
System.out.println(ParaCustGroup);
System.out.println(ParaSlsThroughId);
System.out.println(Active);
lovService.coba(ParaObjGroup,ParaObjCode,ParaProdMatrixId,ParaProdChannelId,ParaProdSalesGroupId,ParaCustGroup,ParaSlsThroughId,Active);
}
and below code for execute stored procedure
#Transactional(propagation = Propagation.REQUIRED, rollbackFor = {SQLException.class, Exception.class })
public void executeSPForInsertData(DataSource ds,String procedureName,Map<String[], Object[]> inputParameter){
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(paramsDataSourceBean).withProcedureName(procedureName);
jdbcCall.execute(inputParameter);
}
But I have a problem cannot set the list type as a parameter in method put:
#ServiceLog(schema = ConstantaVariable.DBDefinition_Var.PARAMS_DB_SCHEMA, sp = ConstantaVariable.PARAMSProcedure_VAR.PR_SP_FAHMI)
#Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class,SQLException.class})
public void coba(List<String> params1,List<String> params2,List<String> params3,List<String> params4,List<String> params5,
List<String> params6,List<String> params7,List<Integer> params8){
Map<String[], Object[]> mapInputParameter = new LinkedHashMap<String[], Object[]>();
mapInputParameter.put("P_OBJT_GROUP", params1);
mapInputParameter.put("P_CODE", params2);
mapInputParameter.put("P_PROD_MATRIX_ID", params3);
mapInputParameter.put("P_PROD_CHANNEL_ID", params4);
mapInputParameter.put("P_PROD_SALES_GROUP_ID", params5);
mapInputParameter.put("P_CUST_GROUP", params6);
mapInputParameter.put("P_SLS_THROUGH_ID", params7);
mapInputParameter.put("P_ACTIVE", params8);
ParamsService.getService().executeSPForInsertData(null,ConstantaVariable.PARAMSProcedure_VAR.PR_SP_FAHMI,mapInputParameter);
}
The type Map<String[], Object[]> is not compatible with what you try to put in: The key is String and the value is List<String>.
There are two solutions:
Change the map to be compatible with the inserted parameters.
Map<String, List<String>> mapInputParameter = new LinkedHashMap<>();
If you need to use the original map type, then you have to change the way you put the parameters into the map.
Map<String[], Object[]> mapInputParameter = new LinkedHashMap<>();
mapInputParameter.put(new String[] { "P_OBJT_GROUP" }, new Object[] { params1 });
mapInputParameter.put(new String[] { "P_CODE" }, new Object[] { params2 });
The drawback is that in further processing you have to check if the array is not empty and cast explicitly from Object to List<String>.
If you want something "more universal and more generic", I'd go for Map<String, List<Object>>. In any way, I find no reason to use an array in the map unless it is explicitly required (I have no information about the executeSPForInsertData method.

convert list into map

I have below list, i want to convert list to map.
SurveyAllocationUsers user1 = new SurveyAllocationUsers();
user1.setSurveyorId("1");
user1.setSurveyorTypeCode("LSR");
SurveyAllocationUsers user2 = new SurveyAllocationUsers();
user2.setSurveyorId("1");
user2.setSurveyorTypeCode("SR");
SurveyAllocationUsers user3 = new SurveyAllocationUsers();
user3.setSurveyorId("2");
user3.setSurveyorTypeCode("LSR");
SurveyAllocationUsers user4 = new SurveyAllocationUsers();
user4.setSurveyorId("2");
user4.setSurveyorTypeCode("SR");
SurveyAllocationUsers user5 = new SurveyAllocationUsers();
user5.setSurveyorId("2");
user5.setSurveyorTypeCode("BG");
List<SurveyAllocationUsers> list = new ArrayList<SurveyAllocationUsers>();
list.add(user1);list.add(user2);list.add(user3);list.add(user4);list.add(user5);
want to convert list to map like below.
Map<String,List<String>> usersMap = new HashMap<String, List<String>>();
map key will be SurveyorId and values will be correspondiing List of SurveyorTypeCode.
Thanks for the help in advance!!!
It should be something like below
userMap.put(user1.getSurveyorId(), new ArrayList<>().add(user1.getSurveyorTypeCode));
userMap.put(user2.getSurveyorId(), new ArrayList<>().add(user2.getSurveyorTypeCode));
It should be something like this:
List<SurveyAllocationUsers> list = new ArrayList<SurveyAllocationUsers>();
list.add(user1);list.add(user2);list.add(user3);list.add(user4);list.add(user5);
Map<String,List<String>> usersMap = new HashMap<String, List<String>>();
for(SurveyAllocationUsers sau: list){
if(!userMap.contains(sau.getSurveyorId())){
userMap.put(sau.getSurveyorId(), new ArrayList<>().add(sau.getSurveyorTypeCode));
}else{
userMap.get(sau.getSurveyorId()).add(sau.getSurveyorTypeCode);
}
}
Note: Code in not complied.
A little bit ugly but solves your problem:
Map<String, List<String>> map = list.stream().collect(toMap(SurveyAllocationUsers::getSurveyorId, p -> new ArrayList(singletonList(p.getSurveyorTypeCode())), (s, a) -> {
s.addAll(a);
return s;
}));
You can try this:
Map<String, List<String>> usersMap = new HashMap<String, List<String>>();
for (SurveyAllocationUsers user : list) {
List<String> typeCodes = new ArrayList<>();
typeCodes.add(user.getSurveyorTypeCode());
usersMap.put(user.getSurveyorId(), typeCodes);
}
Thank you everyone for your reply, I got the solution as below.
List <String>newUserList = null;
Map<String,List<String>> usersMap = new HashMap<String, List<String>>();
for(SurveyAllocationUsers sau: list){
if(usersMap.containsKey(sau.getSurveyorId())){
List <String>myList = usersMap.get(sau.getSurveyorId());
myList.add(sau.getSurveyorTypeCode());
usersMap.put(sau.getSurveyorId(), myList);
}else{
if(sau.getSurveyorId() != null){
newUserList = new ArrayList<String>();
newUserList.add(sau.getSurveyorTypeCode());
usersMap.put(sau.getSurveyorId(), newUserList);
}
}
}
Answer as expected
1 [LSR, SR]
2 [LSR, SR, BG]
It should be like this using Java8
resMap = list.stream().collect(Collectors.groupingBy(SurveyAllocationUsers::getSurveyorId,
Collectors.mapping(SurveyAllocationUsers::getSurveyorTypeCode,Collectors.toList())));
Output: {1=[LSR, SR], 2=[LSR, SR, BG]}

How to merge keys based on value in hashmap?

I am wondering if there was a way to merge keys together based on same values in the Hashmap.
Ex.
A->2
B->1
C->2
The result I am looking for is:
2 - A, C
1 - B
One of the ways is to have your map defined like this:
Map<String,List<String>> multiValueMap = new HashMap();
Or if you don't want to reinvent the wheel, then use Apache MultiMap
You will have to change the data structure to store data in this way. Use a HashMap of ArrayList or Set (as appropriate for you) to do this.
Example
HashMap<Character, Integer> map = new HashMap<>();
map.put('A', 2);
map.put('B', 1);
map.put('c', 2);
// SORTED
HashMap<Integer, List<Character>> sortedMap = new HashMap<>();
ArrayList<Character> list = new ArrayList<>();
for(Map.Entry<Character, Integer> entry : map.entrySet()){
list = sortedMap.get(entry.getValue());
if(list == null){
list = new ArrayList<>();
entry.put(entry.getValue(), list);
}
list.add(entry.getKey());
}
HashMap Reversal
HashMap<String,Integer> aHM = new HashMap<String,Integer>();
HashMap<Integer,ArrayList<String>> aHMrev = new HashMap<Integer,ArrayList<String>>();
//HashMap Reversal
for (String f : aHM.keySet()){
if(aHMrev.get(aHM.get(f)) != null){
ArrayList<String> al = aHMrev.get(aHM.get(f));
al.add(f);
aHMrev.put(aHM.get(f), al);
}
else{
ArrayList<String> al = new ArrayList<String>();
al.add(f);
aHMrev.put(aHM.get(f), al);
}
}
Example
aHM = [LMWEB1B-VMH.log=Group1,PLMWEB1E-VMH.csv=Group3,
LMWEB1A-VMH.log=Group1,
LMWEB1E-VMH.log=Group2,
PLMWEB1D-VMH.csv=Group3,
LMWEB1F-VMH.log=Group2,
PLMWEB1C-VMH.csv=Group3,
PLMWEB1A-VMH.csv=Group2,
PLMWEB1B-VMH.csv=Group3,
PLMDB1-VMH.csv=Group2,
LMWEB1D-VMH.log=Group1,
PLMWEB1F-VMH.csv=Group3,
LMWEB1C-VMH.log=Group1]
aHMrev = {
Group1=[LMWEB1B-VMH.log, LMWEB1A-VMH.log, LMWEB1D-VMH.log,LMWEB1C-VMH.log],
Group2=[LMWEB1E-VMH.log, LMWEB1F-VMH.log,PLMWEB1A-VMH.csv,PLMDB1-VMH.csv],
Group3=[D:\Trash\Logs\Perfmon\PLMWEB1E-VMH.csv,PLMWEB1D-VMH.csv,PLMWEB1C-VMH.csv,PLMWEB1B-VMH.csv,PLMWEB1F-VMH.csv]}
You just create HaspMap like below:
Map<Integer, List<String>> map1 = new HashMap<>();
ArrayList<String> al = new ArrayList<>();
al.add("B");
map1.put(1, al);
al = new ArrayList<>();
al.add("A");
al.add("C");
map1.put(2, al);

Replacing multimap with mapping an element to a collection of elements

I am trying to map a meterId to a list of MeterBlinks that have that Id. I'm mainly confused on how to build the list up for the HashMap.put() call. Code below:
Map<String, List<MeterBlink>> IdToMetersMap = new HashMap<>();
for (MeterBlink meterBlink : createData()) {
List<MeterBlink> meterBlinkList = new ArrayList<>();
meterBlinkList.add(meterBlink);
String meterId = meterBlink.getMeterId();
idToMetersMap.put(meterId, meterBlinkList)
}
I think the issue is that I am creating a new list each time I iterate through but I am not sure how to resolve this.
Use the computeIfAbsent method added in jre 8:
Map<String, List<MeterBlink>> idToMetersMap = new HashMap<>();
for (MeterBlink meterBlink : createData()) {
String meterId = meterBlink.getMeterId();
idToMetersMap.computeIfAbsent(meterId, k -> new ArrayList<>()).add(meterBlinks);
}
Another option in java 8:
Map<String, List<MeterBlink>> idToMetersMap = createData().stream()
.collect(Collectors.groupingBy(MeterBlink::getMeterId));
I like the java8 answer, but here without java8 (without lambda expressions):
Map<String, List<MeterBlink>> idToMetersMap = new HashMap<>();
for (MeterBlink meterBlink : createData()) {
String meterId = meterBlink.getMeterId();
List<MeterBlink> meterBlinkList = idToMetersMap.get(meterId);
//if List doesn't exist create it and put in Map
if (meterBlinkList == null) {
meterBlinkList = new ArrayList<>();
idToMetersMap.put(meterId, meterBlinksList)
}
meterBlinkList.add(meterBlink);
}

How to create a reverse map in java?

I have a map with "task(s)": ["epochdate1", "epochdate2"] how can I reverse this map?
For example
task_1 => [date1, date2, date3, date5]
task_2 => [date4, date5]
task_3 => [date2, date3, date5]
task_4 => [date4, date5]
when reversed it will be
date1 => [task_1]
date2 => [task_1, task_3]
date3 => [task_1, task_3]
date4 => [task_2, task_4]
date5 => [task_1, task_2, task_3, task_4]
Code
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<String, ArrayList<String>> myMap = new HashMap<String, ArrayList<String>>();
ArrayList<String> t1List = new ArrayList<String>();
t1List.add("date1");
t1List.add("date2");
t1List.add("date3");
t1List.add("date5");
ArrayList<String> t2List = new ArrayList<String>();
t2List.add("date4");
t2List.add("date5");
ArrayList<String> t3List = new ArrayList<String>();
t3List.add("date2");
t3List.add("date3");
t3List.add("date5");
ArrayList<String> t4List = new ArrayList<String>();
t4List.add("date4");
t4List.add("date5");
myMap.put("task_1", t1List);
myMap.put("task_2", t2List);
myMap.put("task_3", t3List);
myMap.put("task_4", t4List);
Map<String, ArrayList<String>> reversedMap = Test.getReversedMap(myMap);
}
Just implement it:
Map<String, ArrayList<String>> getReversedMap(Map<String, ArrayList<String>> myMap){
Map<String, ArrayList<String>> result = new HashMap<>();
for(String key : myMap.keySet()){
for(String val : myMap.get(key)){
if(!result.containsKey(val)){
result.put(val, new ArrayList());
}
result.get(val).add(key);
}
}
return result;
}
There are no short cuts. You have to iterate over the entrySet of the original map, and for each date value you find, put a new entry in the new map with the matching task as the first value, or add the task to the list of an existing entry if the date is already in the new map.
I would use Guava for this. Try something like:
Map<K, V> map = ...;
ListMultimap<V, K> inverse = Multimaps.invertFrom(Multimaps.forMap(map),
ArrayListMultimap.<V,K>create());

Categories

Resources