how to define hashmap within hashmap using object of other hashmap - java

HashMap<String, HashMap<String, String>> hm = new HashMap<String, HashMap<String, String>>();
hm.put("Title1","Key1");
for(int i=0;i<2;i++) {
HashMap<String, String> hm1 = new HashMap<String, String>();
hm1.put("Key1","Value1");
}
if i have call Title1 that time they call another hashmap. i want
this type of output
hm<key,value(object hm1)>
hm<key,value)
first hashmap object call second hashmap key

If I correct undestand what you want, use following code
HashMap<String, HashMap<String, String>> hm = new HashMap<>();
HashMap<String, String> hm1 = new HashMap<>();
for(int i=0;i<2;i++) {
hm1.put("Key1","Value1");
}
hm.put("Title1", hm1); // save hm
...
HashMap<String, String> hm2 = hm.get("Title1");
String s = hm2.get("Key1"); // s = "Value1"
OR you can create new class
class HashKey {
private String title;
private String key;
...
// getters, setters, constructor, hashcode and equals
}
and just use HashMap < HashKey, String > hm, for example:
hm.put(new HashKey("Title1", "Key 1"), "Value");
...
String s = hm.get(new HashKey("Title1", "Key 1")); // Value

you can do something likewise,
HashMap<String,HashMap<String,String>> hm = new HashMap<String,HashMap<String,String>>();
HashMap<String,String> hm1 = new HashMap<String,String>();
hm1.put("subkey1","subvalue");
hm.put("Title1",hm1);
HashMap<String,String> newhm = hm.get("Title1");

import java.util.HashMap;
import java.util.Map;
public class MapInMap {
Map<String, Map<String, String>> standards =
new HashMap<String, Map<String, String>>();
void addValues() {
Map<String, String> studentA = new HashMap<String, String>();
studentA.put("A1", "49");
studentA.put("A2", "45");
studentA.put("A3", "43");
studentA.put("A4", "39");
standards.put("A", studentA);
Map<String, String> studentB = new HashMap<String, String>();
studentB.put("B1", "29");
studentB.put("B2", "25");
studentB.put("B3", "33");
studentB.put("B4", "29");
standards.put("B", studentB);
}
void disp() {
for (Map.Entry<String, Map<String, String>> entryL1 : standards
.entrySet()) {
System.out.println("Standard :" + entryL1.getKey());
for (Map.Entry<String, String> entryL2 : entryL1.getValue()
.entrySet()) {
System.out.println(entryL2.getKey() + "/" + entryL2.getValue());
}
}
}
public static void main(String args[]) {
MapInMap inMap = new MapInMap();
inMap.addValues();
inMap.disp();
}
}

Related

How to save List Of HashMap in android?

I have a hashmap of string
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("name", name);
hashMap.put("number", number);
hashMap.put("profileImage", image);
and a List of Hashmap
List<HashMap<String, String>> recents = new ArrayList<>();
recents.add(hashMap);
Now I have to save this list
I have tried using https://github.com/pilgr/Paper to save this List
Paper.book().write("recents", recents);
but i can't get the list back
List<HashMap<String, String>> list = Paper.book().read("recents");
HashMap<String,String> hashMap = list.get(0);
String name = hashMap.get("name");
String number = hashMap.get("number");
String image = hashMap.get("profileImage");
Uses of the code
actually I'm passing this list to recycelerViewAdapeter and from there in OnBindViewHolder() I'm getting all the Hashmap values and displaying it to user
Saving Data Code
Paper.init(this);
List<HashMap<String, String>> recents = new ArrayList<>();
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("name", name);
hashMap.put("number", number);
hashMap.put("profileImage", image);
recents.add(hashMap);
Paper.book().write("recents", contacts);
Receiving Data Code
Paper.init(requireActivity());
recyclerView = view.findViewById(R.id.recyclerView);
List<HashMap<String, String>> list = Paper.book().read("recents");
Adapter = new Adapter(requireActivity(), list);
recyclerView.setAdapter(Adapter);
You can use Gson and SharedPreferences to do the same.
implementation 'com.google.code.gson:gson:2.8.9'
Example:
private SharedPreferences sp;
private HashMap<String, Boolean> favs;
....
....
public void addFavourite(String wall_name) {
favs = getFavourites();
favs.put(wall_name, true);
setFavourties();
}
public void removeFav(String wall_name) {
favs = getFavourites();
favs.put(wall_name, false);
setFavourties();
}
private void setFavourties() {
SharedPreferences.Editor pe = sp.edit();
Gson gson = new Gson();
String j = gson.toJson(favs);
pe.putString("Favourites", j);
pe.apply();
}
public HashMap<String, Boolean> getFavourites() {
Gson gson = new Gson();
String j = sp.getString("Favourites", null);
if (j != null) {
Type stringBooleanMap = new TypeToken<HashMap<String, Boolean>>() {
}.getType();
return gson.fromJson(j, stringBooleanMap);
} else {
return new HashMap<>();
}
}

Java flatten nested Maps and concatenate keys

I have a HashMap as below:
Map<String,Object> map = new HashMap<>();
Map<String,Object> map1 = new HashMap<>();
map1.put("key1", "value1");
Map<String,Object> map2 = new HashMap<>();
Map<String,Object> map3 = new HashMap<>();
map3.put("key2", "value2");
map2.put("map3", map3);
map.put("map1", map1);
map.put("map2", map2);
map.put("key3", "value3");
I want to flatten it. Expected output is:
[map1.key1, value1]
[map2.map3.key2, value2]
[key3, value3]
...
This can be done using simple for loops with following code:
public static Map<String, String> flat(Map<String, Object> input){
Map<String, String> toReturn = new HashMap<>();
for (Map.Entry<String, Object> entry: input.entrySet()) {
if(entry.getValue() instanceof Map){
Map<String, Object> innerMap = (Map<String, Object>)entry.getValue();
for(Map.Entry<String, Object> innerEntry: innerMap.entrySet()) {
if(innerEntry.getValue() instanceof Map){
...
...
}
else {
toReturn.put(entry.getKey() + "." + innerEntry.getKey(), innerEntry.getValue().toString());
}
}
} else {
toReturn.put(entry.getKey(), entry.getValue().toString());
}
}
return toReturn;
}
Code to do this recursively:
public static Map<String, String> flat(Map<String, Object> input){
Map<String, String> toReturn = new HashMap<>();
rec(toReturn, input, new ArrayList<>());
return toReturn;
}
public static void rec(Map<String, String> toReturn, Map<String, Object> input, List<String> keys) {
for (Map.Entry<String, Object> entry: input.entrySet()) {
if(entry.getValue() instanceof Map){
keys.add(entry.getKey());
rec(toReturn, (Map<String, Object>) entry.getValue(), keys);
} else {
final StringBuffer key = new StringBuffer();
if(keys.size() > 0) {
keys.forEach(x -> key.append(x).append("."));
}
key.append(entry.getKey());
toReturn.put(key.toString(), entry.getValue().toString());
}
}
if(keys.size() > 0) {
keys.remove(keys.size() - 1);
}
}
How do I achieve this using Java Stream API ?
This is generally the same solution as in the mentioned link but with some update to work with entrySet() and add a key from containing map as a prefix:
public class FlattenMap {
public static Stream<Map.Entry<String, Object>> flatten(Map.Entry<String, Object> entry) {
if (entry.getValue() instanceof Map<?, ?>) {
Map<String, Object> nested = (Map<String, Object>) entry.getValue();
return nested.entrySet().stream()
.map(e -> new AbstractMap.SimpleEntry(entry.getKey() + "." + e.getKey(), e.getValue()))
.flatMap(FlattenMap::flatten);
}
return Stream.of(entry);
}
public static void main(String[] args) {
Map<String,Object> map = new HashMap<>();
Map<String,Object> map1 = new HashMap<>();
map1.put("key1", "value1");
Map<String,Object> map2 = new HashMap<>();
Map<String,Object> map3 = new HashMap<>();
map3.put("key2", "value2");
map2.put("map3", map3);
map.put("map1", map1);
map.put("map2", map2);
map.put("key3", "value3");
// collecting to List of entries
map.entrySet().stream()
.flatMap(FlattenMap::flatten)
.collect(Collectors.toList())
.forEach(System.out::println);
// collecting entries back to flattened map
Map<String, Object> remapped = map.entrySet().stream()
.flatMap(FlattenMap::flatten)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
remapped.entrySet().stream()
.forEach(e -> System.out.printf("[%s, %s]%n", e.getKey(), e.getValue()));
}
}
It prints results:
map2.map3.key2=value2
map1.key1=value1
key3=value3
[key3, value3]
[map2.map3.key2, value2]
[map1.key1, value1]

Can't retrieve Double from HashMap<Integer, Double>

Somehow I can't retrieve a Double from a HashMap I've made using Gson.
Map<Integer, Double> ratingMap = (Map<Integer, Double>) new GsonBuilder()
.create().fromJson(json, Map.class);
Integer ifilmId = filmId;
Double rating = ratingMap.get(ifilmId);
In this code I've veried that the ratingMap contains {2=5.0}, but when I do ratingMap.get(ifilmId) (where I've verified that ifilmId is in fact 2), the variable rating is null. Am I missing something here?
I create the HashMap in the following way:
if (json.equals("")) {
// noting ever saved
ratingMap = new HashMap<Integer, Integer>();
ratingMap.put(filmId, rating);
} else {
ratingMap = (Map<Integer, Integer>) new GsonBuilder().create()
.fromJson(json, Map.class);
ratingMap.put(Integer.valueOf(filmId), rating);
}
I let Gson format the Integer to a Double, and that seems to work fine but I can't retrieve it.
The total code, including saving to Androids SharedPreferences
public void saveRating(int rating, int filmId) {
SharedPreferences sharedPref = context.getSharedPreferences(
LOCAL_MEM_KEY, 0);
String json = sharedPref.getString(LOCAL_MAP_RATING_KEY, "");
Map<Integer, Integer> ratingMap;
if (json.equals("")) {
// noting ever saved
ratingMap = new HashMap<Integer, Integer>();
ratingMap.put(filmId, rating);
} else {
ratingMap = (Map<Integer, Integer>) new GsonBuilder().create()
.fromJson(json, Map.class);
ratingMap.put(Integer.valueOf(filmId), rating);
}
json = new GsonBuilder().create().toJson(ratingMap, Map.class);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(LOCAL_MAP_RATING_KEY, json);
editor.commit();
}
/*
* returns null if no rating found
*/
public Map<Integer, Integer> getRatingFor(int filmId) {
SharedPreferences sharedPref = context.getSharedPreferences(
LOCAL_MEM_KEY, 0);
String json = sharedPref.getString(LOCAL_MAP_RATING_KEY, "");
if (json.equals("")) {
return null;
}
Map<Integer, Integer> ratingMap = (Map<Integer, Integer>) new GsonBuilder()
.create().fromJson(json, Map.class);
Log.d("map", ratingMap.toString());
Integer ifilmId = filmId;
Integer rating = ratingMap.get(ifilmId);
if(rating == null) { //because of this we have to prevent a 0 rating
return null;
} else {
Map<Integer, Integer> returnMap = new HashMap<Integer, Integer>();
returnMap.put(filmId, rating.intValue());
return returnMap;
}
}
Make sure your not passing a null variable when saving
saveRating(int rating, int filmId){
Log.d(TAG, String.valueOf(rating));
}
if (json.equals("")) {
// noting ever saved
ratingMap = new HashMap<Integer, Double>(); <--- Double not Integer
ratingMap.put(filmId, 5.0);
} else {
ratingMap = (Map<Integer, Double>) new GsonBuilder().create()
.fromJson(json, Map.class); <--- double not Integer
ratingMap.put(Integer.valueOf(filmId), 5.0);
}
Make sure when using Doubles to
use 5.0
not 5
public void saveRating(Double rating, int filmId) {
SharedPreferences sharedPref = context.getSharedPreferences(LOCAL_MEM_KEY, 0);
String json = sharedPref.getString(LOCAL_MAP_RATING_KEY, "");
Map<Integer, Double> ratingMap;
if (json.equals("")) {
// noting ever saved
ratingMap = new HashMap<Integer, Double>();
} else {
ratingMap = (Map<Integer, Double>) new GsonBuilder().create().fromJson(json, Map.class);
}
ratingMap.put(filmId, rating);
ratingMap.put(3, 5.0d); // JUST FOR TEST
json = new GsonBuilder().create().toJson(ratingMap, Map.class);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(LOCAL_MAP_RATING_KEY, json);
editor.commit();
}
/*
* returns null if no rating found
*/
public Map<Integer, Double> getRatingFor(int filmId) {
SharedPreferences sharedPref = context.getSharedPreferences(LOCAL_MEM_KEY, 0);
String json = sharedPref.getString(LOCAL_MAP_RATING_KEY, "");
if (json.equals("")) {
return null;
}
Map<Integer, Double> ratingMap = (Map<Integer, Double>) new GsonBuilder().create().fromJson(json, Map.class);
Log.d("map", ratingMap.toString());
Log.d("map", ratingMap.get(3) + ""); // JUST FOR TEST
Integer ifilmId = filmId;
Double rating = ratingMap.get(ifilmId);
if (rating == null) { //because of this we have to prevent a 0 rating
return null;
} else {
Map<Integer, Double> returnMap = new HashMap<Integer, Double>();
returnMap.put(filmId, rating);
return returnMap;
}
}

Reduce-Side Join ArrayIndexOutOfBounds Exception using Java

trying to run a Reduce Side join on 3 datasets. Unfortunalyy, i keep getting an ArrayIndex exception. I have tried to handle it with a try & Catch, but to no avail. Can someone please recommend a solution?
package Joins;
import java.io.IOException;
import java.util.*;
import java.util.Map.Entry;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.Reducer;
public class JoinReducer extends Reducer<Text, Text, Text, Text>
{
Map<String, String> divStkJoin = new HashMap<String, String>();
Map<String, String> divStkMetaJoin = new HashMap<String, String>();
Map<String, String> stockData = new HashMap<String, String>();
Map<String, String> metaData = new HashMap<String, String>();
Map<String, String> divData = new HashMap<String, String>();
Text k = new Text();
Text v = new Text();
public void setup(Context context)
{
metaData.clear();
divData.clear();
stockData.clear();
divStkJoin.clear();
divStkMetaJoin.clear();
}
public void reduce(Text keys, Iterable<Text> values, Context context)
{
Iterator it = values.iterator();
while(it.hasNext()){
String [] keyLine = keys.toString().split(",");
String valueLine = values.toString();
try {
if(keyLine[4].equals("_s"))
{
String keyLineStock = keyLine[0] + "," + keyLine[1] +"," + keyLine[2] + "," + keyLine[3];
stockData.put(keyLineStock, valueLine);
}
else if(keyLine[4].equals("_d"))
{
String keyLineDiv = keyLine[0] + "," + keyLine[1] +"," + keyLine[2] + "," + keyLine[3];
divData.put(keyLineDiv, valueLine);
}
else if (keyLine[1].equals("_m"))
{
String keyLineMeta = keyLine[0];
metaData.put(keyLineMeta, valueLine);
}
else
return;
} catch (ArrayIndexOutOfBoundsException e){return;}
}
//JOINS
for(Entry<String, String> entryStock: stockData.entrySet())
for(Entry<String, String> entryDiv: divData.entrySet())
{
if(entryStock.getKey().equals(entryDiv.getKey()))
{
divStkJoin.put(entryStock.getKey(), entryStock.getValue()+ ","+ entryDiv.getValue());
}
}
for(Entry<String, String> entrydivStkJoin: divStkJoin.entrySet())
{
String [] entrydivStkJoinKeyArr = entrydivStkJoin.getKey().toString().split(",");
for(Entry<String, String> meta: metaData.entrySet())
{
String [] metaArr = meta.getKey().split(",");
if(metaArr[0].equals(entrydivStkJoinKeyArr[1]))
{
divStkMetaJoin.put(entrydivStkJoin.toString(), meta.getValue());
}
}
}
}
public void cleanup(Context context) throws IOException, InterruptedException
{
String keyJ;
String valJ;
for(Map.Entry<String, String> entry : divStkMetaJoin.entrySet())
{
keyJ=entry.getKey();
valJ=entry.getValue();
Text k = new Text(keyJ);
Text v = new Text(valJ);
context.write(k, v);
}
}
}
I think the error comes from this line:
if(keyLine[4].equals("_s")),
My solucion would be ckecking if keyLine is null or if keyLine < 4:
if(ss == null || ss.length()<4){
return;
}

Wrong convert Object from JSON

First, sorry for my poor English.
Second, my problem.
I trying convert to JSON and back this structure:
class Revision{
private String auth;
private HashMap<String, List<HashMap<String, Object>>> rev;
public String getAuth(){
return auth;
}
public HashMap<String, List<HashMap<String, Object>>> getRev(){
return rev;
}
public void setAuth(String auth){
this.auth = auth;
}
public void setRev(HashMap<String, List<HashMap<String, Object>>> rev){
this.rev = (HashMap<String, List<HashMap<String, Object>>>) rev.clone();
}
public String toString(){
return "Auth: " + auth + ", rev: " + rev;
}
}
I do it with this code:
public static void main (String[] argc){
Gson gson = new Gson();
Revision revision = new Revision();
HashMap<String, List<HashMap<String, Object>>> HM = new HashMap<String, List<HashMap<String, Object>>>();
List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> HMin = new HashMap<String, Object>();
HMin.put("id", 12);
HMin.put("type", "toster");
list.add(HMin);
HM.put("mark", list);
revision.setRev(HM);
revision.setAuth("ololo");
String json = gson.toJson(revision);
Revision test = new Gson().fromJson(json, Revision.class);
System.out.println(json);
System.out.println(revision);
System.out.println(test);
}
In finally I get this result:
{"auth":"ololo","rev":{"mark":[{"id":12,"type":"toster"}]}}
Auth: ololo, rev: {mark=[{id=12, type=toster}]}
Auth: ololo, rev: {mark=[{id=java.lang.Object#1c672d0, type=java.lang.Object#19bd03e}]}
As you can see, after convertation, Object-type parameters incorrect.
Please, can you tell me, how I can fix this trouble?
Thank you in advance!
Try this out and see if it is working? Yeah, I know you want to support Object type, but this is just for try sake.
Gson gson = new Gson();
Revision revision = new Revision();
HashMap<String, List<HashMap<String, String>>> HM = new HashMap<String, List<HashMap<String, String>>>();
List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
HashMap<String, String> HMin = new HashMap<String, String>();
HMin.put("id", "12");
HMin.put("type", "toster");
list.add(HMin);
HM.put("mark", list);
revision.setRev(HM);
revision.setAuth("ololo");
String json = gson.toJson(revision);
Revision test = new Gson().fromJson(json, Revision.class);
System.out.println(json);
System.out.println(revision);
System.out.println(test);
[Edited]
Now try this snippet directly, with a respective change in Revision class.
Revision test = new Gson().fromJson("{\"auth\":\"ololo\",\"rev\":{\"mark\":[{\"id\":12,\"type\":13}]}}", Revision.class);
System.out.println(test);
Change this in Revision class to this,
HashMap<String, List<HashMap<String, Integer>>> HM = new HashMap<String, List<HashMap<String, Integer>>>();
This is to make sure that its working good with specific type. If it does, we will be sure that it can't work with Obejct type somehow. Then you can file a bug there, for their good. And for the time being you can switch to some other API, if you like to. You can find few options here.

Categories

Resources