Java Print Value Object on Map<String, Object> - java

I set list on another class
List<DataModel> dataList = new ArrayList<DataModel>();
parsed on class
for(DataModel list : dataList) {
final String[] data = {list.getVar_a(), list.getVar_b()};
System.out.println("out data");
System.out.println(list.getVar_a());
System.out.println(list.getVar_b());
}
this prints data
out data
val_a
val_b
Model Class
class DataModel {
private String var_a, var_b;
//Getter & Setter
}
But now, I use and set map on another class and I'm not implementing a model class because in real case it has too many variables.
Map<String, Object> mapData = new LinkedHashMap<String, Object>();
when I set data on map, its result from database
Map<String, Object> map = new LinkedHashMap<String, Object>();
msg = (String) cs.getObject(5);
rs = (ResultSet) cs.getObject(4);
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
if(rs.next()){
int jml = 0;
do {
Map<String, Object> data = new LinkedHashMap<>();
for (int i = 1; i <= count; i++ ) {
String name = rsmd.getColumnName(i);
data.put(name, rs.getObject(name));
}
map.put(""+jml, data);
jml++;
} while(rs.next());
setStatus(SUCCESS);
setMessage(msg);
} else {
LOG.info(NO_DATA_FOUND);
}
parsed on class
for(Map.Entry<String,Object> list : mapData.entrySet()) {
String key = list.getKey();
Object val = list.getValue();
System.out.println("out data");
System.out.println(key);
System.out.println(val);
}
this prints data
out data
0
{var_a=val_a, var_b=val_b}
I want to get value on object like this
out data
val_a
val_b

Change your Map for loop to:
for(Map.Entry<String,Object> list : mapData.entrySet()) {
DataModel value = (DataModel) list.getValue();
System.out.println("out data");
System.out.println(value.getVar_a());
System.out.println(value.getVar_b());
}

First you have a map of object, and what you really need is a Map of Map.
Here is your reading a map of object.
for(Map.Entry<String,Object> list : mapData.entrySet()) {
String key = list.getKey();
Object val = list.getValue();
System.out.println("out data");
System.out.println(key);
System.out.println(val);
}
What you really need is a map of map as I am showing below.
Map<String, Map<String, Object>> map = new LinkedHashMap<String, Map<String, Object>>()
Now if you read it as map of map, You can have the result that you need.
0 : {a1:v1, a2:v2, etc...},
1 : {a2:v2, a2:v2, etc...},
2 : {a3:v3, a3:v3, etc...}
for(Map.Entry<String,Map<String, Object> list : mapData.entrySet()) {
String key = list.getKey();
System.out.println("out data");
for(Map.Entry<String,Object> innermap : list.getValue().entrySet()) {
//System.out.println(innermap.getKey());
System.out.println(innermap.getValue());
}
}

Related

How to make 3 dimensional array in java?

I have a query string like
"1_timestamp=201612312&1_user=123&2_timestamp=20145333&2_user=5432";
But I want to make them in array like below.
array(
0 => (
timestamp = 201612312,
user = 123,
),
1 => (
timestamp = 201612312,
user = 123,
),
);
I'm sorry to show you php type of array though I'm new to java.
How do I make it something like that?
Thank you
This is the closest structure to what you are doing in php, and if your data has more fields it can be easily added to the Data class:
import java.util.ArrayList;
import java.util.List;
class Data {
int timestamp;
int user;
Data(int ts, int user) {
this.timestamp = ts;
this.user = user;
}
}
public class Test {
public static void main(String[] args) {
List<Data> data = new ArrayList<Data>();
Data d1 = new Data(201612312, 123);
Data d2 = new Data(201612312, 123);
data.add(d1);
data.add(d2);
System.out.println(data.get(1).user);
}
}
You can do it without writing a class. You can use it like this.
Map<String, String> map1 = new HashMap<String, String>();
map1.put("1_timestamp", "201612312");
map1.put("1_user", "123");
Map<String, String> map2 = new HashMap<String, String>();
map2.put("2_timestamp", "20145333");
map2.put("2_user", "5432");
List<Map<String,String> mapList = new ArrayList<Map<String, String>>();
mapList.add(map1);
mapList.add(map2);
for (Map<String, String> map : list) {
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + " - " + entry.getValue());
}
}

java print values inside hashmap

i have HashMap and its have data,
i connect to database by xmlrpc by jetty9
i am call this function by java client , by this code
Object params[] = new Object[]{stString};
HashMap v1;
v1 = (HashMap<String, Object[]>)server.execute("DBRamService.getRmsValues", params);
i need to print it in my java client , how can i make it ?
this is my function that get data from datebase
HashMap<String, Object[]> result = new HashMap<String, Object[]>();
ArrayList<Double> vaArrL = new ArrayList<Double>();
try {
// i have connected to postgres DB and get data
while (rs.next()){
vaArrL.add(rs.getDouble("va"));
}
int sz = vaArrL.size();
result.put("va", vaArrL.toArray(new Object[sz]));
} catch ( Exception e ) {
System.out.println(e);
e.printStackTrace();
}
return result; }
Following is the snippet to loop through the vArrL and printing the values:
for (int i=0;i<vaArrL.size();i++) {
System.out.println(vaArrL.get(i));
}
Looping through HashMap using Iterator:
Iterator<Entry<String, Object[]>> it = result.entrySet().iterator();
while (it.hasNext()) {
Entry<String, Object[]> pairs = (Entry<String, Object[]>) it.next();
for(Object obj: pairs.getValue()) {
System.out.println(obj);
}
}
Here is how to iterate through a HashMap and get all the keys and values:
// example hash map
HashMap<String, Object[]> v1 = new HashMap<String, Object[]>();
v1.put("hello", new Object[] {"a", "b"});
// print keys and values
for(Map.Entry<String, Object[]> entry : v1.entrySet()) {
System.out.println("Key: " + entry.getKey() + " Values: " + Arrays.asList(entry.getValue()));
}
If you need to print in a different format, you can iterate over the elements of the value array like this:
for(Map.Entry<String, Object[]> entry : v1.entrySet()) {
System.out.println("Key:");
System.out.println(entry.getKey());
System.out.println("Values:");
for (Object valueElement : entry.getValue()) {
System.out.println(valueElement);
}
}

Searching String Array item in a nested HashMap

I have a nested HashMap (outer_map), which has another HashMap inside of it as a value (inner_map), such implemented as
Map<String, HashMap<String, String>> outer_map = new HashMap<String, HashMap<String, String>>();
Map<String, String> inner_map = new HashMap<String, String>();
The figure below illustrates the whole structures of the maps:
To make the long story short, I need to compare and search values inside the outer_map's vlaue (inner_map) by String Array items, and then produce another String Array to add matched items.
If the String Array has there elements which are the same as one of the inner_map's random (for example; value2, value1, and value7) values, how can I search and compare these items to add to another String Array?
The latest code snippet I tried and I couldn't succeed:
if( !( theStringArray.equals("") ) )
{
while( outer_map.keySet().iterator().hasNext() )
{
for( int i=0; i <= theStringArray.length; i++)
{
// outer_map keys are order as 1,2,3,..,8
theStringArray[i] = outer_map.get(String.valueOf(i+1)).get("key1");
...
}
}
}
EDIT: Map generating function
private void parse(String in) throws IOException
{
reader = new JsonReader(new StringReader(in));
...
int nodeCounter = 1;
while(reader.hasNext())
{
...
String nameAsKey1 = "blabla"; // value1
inner_map.put("name", nameAsKey1);
String surnameAsKey2 = "blabla"; // value2
inner_map.put("surname", surnameAsKey2);
...
outer_map.put(String.valueOf(nodeCounter), (HashMap<String, String>) inner_map);
inner_map = new HashMap<String, String>();
nodeCounter++;
}
}
EDIT: I don't know how I can explain the issue more clearly, but may be this will help to understand about it: Map structure
I assume you have an array of String and a Map of map. Now you want to search the value fields of inner map against the array of String and if make a new string array with matching values.
If that is the case the below program will help you..
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class InnerMapSearch {
public static void main(String[] args) {
Map<String, HashMap<String, String>> outer_map = new HashMap<String, HashMap<String, String>>();
Map<String, String> inner_map = new HashMap<String, String>();
String[] searchParams = {"blabla1", "blabla3", "blabla20"};
//Populating the map
int reader = 1;
while (reader < 10) {
String nameAsKey1 = "blabla" + reader; // value1
inner_map.put("name", nameAsKey1);
String surnameAsKey2 = "blabla" + reader; // value2
inner_map.put("surname", surnameAsKey2);
outer_map.put(String.valueOf(reader), (HashMap<String, String>) inner_map);
inner_map = new HashMap<String, String>();
reader++;
}
//Searching
Set<String> searchResults = new HashSet<String>(); // Using set to avoid duplicate
// Iterate over the outer map
for(String key : outer_map.keySet()){
// Iterate through each inner_map value of outer map
for(Entry<String, String> innerEntry : outer_map.get(key).entrySet()){
// Iterate through the list of search params and see if its present in inner_hashmap
for(String searchParam : searchParams){
if(searchParam.equals(innerEntry.getValue())){
// The search parameter is in inner map so adding to result.
searchResults.add(searchParam);
}
}
}
}
// Converting the list to an array.
String[] searchResultsArray = searchResults.toArray(new String[searchResults.size()]);
}
}

How can i fetch all data present in Map<String,Map<String,String>> data structure?

i want to retrieve all data that are present in my data structure, which is of type Map of Maps.The data structure is mentioned below.
public static Map<String, Map<String, String>> hourlyMap = new HashMap<String, Map<String, String>>();
i need all the data that are stored in the map irrespective of key.
This may help you
Map<String,Map<String,String>> hourlyMap = new HashMap<String,Map<String,String>>();
for(Map<String,String> i:hourlyMap.values()){
// now i is a Map<String,String>
for(String str:i.values()){
// now str is a value of map i
System.out.println(str);
}
}
Try:
Set<String> allData = new HashSet<>(); // will contain all the values
for(Map<String, String> map : hourlyMap.values()) {
allData.addAll(map.values());
}
for (String outerKey: hourlyMap.keySet()) {
// outerKey holds the Key of the outer map
// the value will be the inner map - hourlyMap.get(outerKey)
System.out.println("Outer key: " + outerKey);
for (String innerKey: hourlyMap.get(outerKey).keySet()) {
// innerKey holds the Key of the inner map
System.out.println("Inner key: " + innerKey);
System.out.println("Inner value:" + hourlyMap.get(outerKey).get(innerKey));
}
}

Search a HashMap in an ArrayList of HashMap

I have an ArrayList of HashMap. I want to search a HashMap in it but unable to find a way to achieve this. Please suggest me how it can be done?
Thanks.
Answer to your question the way i understood it!
for (HashMap<String, String> hashMap : yourArrayList)
{
// For each hashmap, iterate over it
for (Map.Entry<String, String> entry : hashMap.entrySet())
{
// Do something with your entrySet, for example get the key.
String sListName = entry.getKey();
}
}
Your Hashmap might use other types, this one uses Strings.
See if this helps:
#Test
public void searchMap() {
List<Map<String, String>> listOfMaps = new ArrayList<Map<String,String>>();
Map<String, String> map1 = new HashMap<String, String>();
map1.put("key1", "value1");
Map<String, String> map2 = new HashMap<String, String>();
map1.put("key2", "value2");
Map<String, String> map3 = new HashMap<String, String>();
map1.put("key3", "value3");
listOfMaps.add(map1);
listOfMaps.add(map2);
listOfMaps.add(map3);
String keyToSearch = "key2";
for (Map<String, String> map : listOfMaps) {
for (String key : map.keySet()) {
if (keyToSearch.equals(key)) {
System.out.println("Found : " + key + " / value : " + map.get(key));
}
}
}
}
Cheers!
Object myObj;
Object myKey;
//Traverse the list
for(HashMap curMap : listOfMaps){
//If this map has the object, that is the key doesn't return a null object
if( (myObj = curMap.get(myKey)) != null) {
//Stop traversing because we are done
break;
}
}
//Act on the object
if(myObj != null) {
//TODO: Do your logic here
}
If you are looking to get the reference to the Map instead of the object (for whatever reason) same process applies, except you just store the reference to the map:
Map myMap;
Object myKey;
//Traverse the list
for(HashMap curMap : listOfMaps){
//If this map has the object, that is the key doesn't return a null object
if(curMap.get(myKey) != null) {
//Store instance to the map
myMap = curMap;
//Stop traversing because we are done
break;
}
}
//Act on the map
if(myMap != null) {
//TODO: Do your logic here
}
Try below improved code for searching the key in a list of HashMap.
public static boolean searchInMap(String keyToSearch)
{
boolean returnVal = false;
List<Map<String, String>> listOfMaps = new ArrayList<Map<String, String>>();
Map<String, String> map1 = new HashMap<String, String>();
map1.put("key1", "value1");
Map<String, String> map2 = new HashMap<String, String>();
map1.put("key2", "value2");
Map<String, String> map3 = new HashMap<String, String>();
map1.put("key3", "value3");
listOfMaps.add(map1);
listOfMaps.add(map2);
listOfMaps.add(map3);
for (Map<String, String> map : listOfMaps)
{
if(map.containsKey(keyToSearch))
{
returnVal =true;
break;
}
}
return returnVal;
}
The Efficient way i've used to search a hashmap in an arraylist without using loops. Since loop makes execution time longer
try{
int index = list.indexOf(map); // map is your map to find in ArrayList
if(index>=0){
HashMap<String, String> map = array_list.get(index);
// Here you can get your values
}
}
catch(Exception e){
e.printStackTrace();
Log.i("HashMap","Not Found");
}
if you have an ArrayList like this one: ArrayList<HashMap<String, String>>
and you want to compare one of the values inside the HashMap try this code.
I use it to compare settings of my alarm notifications.
for (HashMap<String, String> map : AlarmList) {
for (String key : map.keySet())
{
if (key.equals("SendungsID"))
{
if(map.get(key).equals(alarmMap.get("AlarmID")))
{
//found this value in ArrayList
}
}
}
}

Categories