How can I get a column of value from hashmap - java

I have a hashmap listview with four key and multiple value that retrieve from database. For now I can get all the value from the key of FOODID2, FOODNAME2, PRICE2, RATING2 and display via toast. But what I want is just the value from the key (FOODID2) to be display. Is it possible to do it? And correct me if I'm wrong. Thanks!
for (int i=0; i<data.size(); i=i+4)
{
HashMap<String, String> map = new HashMap<String, String>();
map.put(FOODID2, (String) data.get(i));
map.put(FOODNAME2, (String) data.get(i+1));
map.put(PRICE2, (String) data.get(i+2));
map.put(RATING2, (String) data.get(i+3));
LIST2.add(map);
for(Entry<String, String> entry: map.entrySet())
{
if(entry.getKey().equals(FOODID2))
{
Toast.makeText(getApplicationContext(),
"EXISTS " + entry.getKey(), Toast.LENGTH_LONG)
.show();
}
}
}

get entry.getKey() and just validate this
if(entry.getKey().equls("YOUR KEY NAME"))
{
// here u can print the toaste.
}

Why not just map.get(FOODID2)? That is, something like this...
StringBuilder sb = new StringBuilder();
for (HashMap<String, String> map : LIST2) {
if (sb.length() > 0) {
sb.append(", ");
}
sb.append("EXISTS " + map.get(FOODID2));
}

you can usehashMap.get(key) to get the value of a particular key.
or in your code you can use a if statement to check for the key.

You can loop map.keySet() to get all the keys, loop map.values() to get all the values.

Related

Comparing HashMaps for Matches and Mismatches

I have two HashMaps that is expected to hold Keys which are identical, but expect some differences on their values, and perhaps source/target does not contain the key.
Map<String, Double> source = repository.getSourceData();
Map<String, Double> target = repository.getTargetData();
I'm looking to produce a report with Matched data values for the keys, Mismatched data values for keys, and finally Keys exist in only one map.
Using Java 8's computeIfPresent() or computeIfAbsent(), how can I achieve this? I need to iterate through source map, check if a key exists in the target map, if exists, inspect values are matching or not. when matched, output result to matched collection. when mismatched, output to mismatched container, and finally output no key exists in target.
I don't think computeIfPresent or computeIfAbsent are appropriate for this:
Map<String, Double> source = repository.getSourceData();
Map<String, Double> target = repository.getTargetData();
Map <String, Double> matched = new HashMap<>();
Map <String, List<Double>> mismatched = new HashMap<>();
Map <String, String> unmatched = new HashMap<>();
for (String keySource : source.keySet()) {
Double dblSource = source.get(keySource);
if (target.containsKey(keySource)) { // keys match
Double dblTarget = target.get(keySource);
if (dblSource.equals(dblTarget)) { // values match
matched.put(keySource, dblSource);
} else { // values don't match
mismatched.put(keySource, new ArrayList<Double>(Arrays.toList(dblSource, dblTarget)));
}
} else { // key not in target
unmatched.put(keySource, "Source");
}
}
for (String keyTarget : target.keySet()) { // we only need to look for unmatched
Double dblTarget = target.get(keyTarget);
if (!source.containsKey(keyTarget)) {
unmatched.put(keyTarget, "Target");
}
}
// print out matched
System.out.println("Matched");
System.out.println("=======");
System.out.println("Key\tValue");
System.out.println("=======");
for (String key : matched.keySet()) {
System.out.println(key + "\t" + matched.get(key).toString());
}
// print out mismatched
System.out.println();
System.out.println("Mismatched");
System.out.println("=======");
System.out.println("Key\tSource\tTarget");
System.out.println("=======");
for (String key : mismatched.keySet()) {
List<Double> values = mismatched.get(key);
System.out.println(key + "\t" + values.get(0) + "\t" + values.get(1));
}
// print out unmatched
System.out.println();
System.out.println("Unmatched");
System.out.println("=======");
System.out.println("Key\tWhich\tValue");
System.out.println("=======");
for (String key : unmatched.keySet()) {
String which = unmatched.get(key);
Double value = null;
if ("Source".equals(which)) {
value = source.get(key);
} else {
value = target.get(key);
}
System.out.println(key + "\t" + which + "\t" + value);
}

How to get value from Map key in java

I am trying to receive message attributes from Amazon SQS with the following code :
Map<String, com.amazonaws.services.sqs.model.MessageAttributeValue> attributes = new HashMap<String, com.amazonaws.services.sqs.model.MessageAttributeValue>();
attributes = message.getMessageAttributes();
for(String key: attributes.keySet()){
System.out.println(key + " - "+ attributes.get(key));
}
and it returns the output:
project - {StringValue: 25,StringListValues: [],BinaryListValues: [],DataType: String}
I want to get only the value 25. How do I do that?
Try this:
attributes.get("project").getStringValue()
References:
How to extract from a Map the value of a given key?
How to extract a String Value of a given MessageAttributeValue?
Because that's the object of value type com.amazonaws.services.sqs.model.MessageAttributeValue declared in your Map .
You need to get the value out of that object like the way you would normally do :
for(String key: attributes.keySet()){
com.amazonaws.services.sqs.model.MessageAttributeValue object = attributes.get(key);
//some method to get that 25 value
System.out.println(key + " - "+ object.getStringValue());
}
You need to loop on your map here is an example to show you how to get the values of the map:
I have a : Map<String, Object> map = new HashMap<String, Object>();
for (Entry<String, Object> entry : map.entrySet()) {
System.out.println("entry key : "+entry.getKey());
System.out.println("Object value :"+entry.getValue());
}
use this (library org.json.JSONObject; [java-json.jar])
Map<String, com.amazonaws.services.sqs.model.MessageAttributeValue> attributes = new HashMap<String, com.amazonaws.services.sqs.model.MessageAttributeValue>();
attributes = message.getMessageAttributes();
for(String key: attributes.keySet()){
System.out.println(key + " - "+ attributes.get(key));
try {
JSONObject json = new JSONObject(attributes.get(key));
System.out.println(json.get("StringValue"));
} catch (JSONException e) {
e.printStackTrace();
}
}

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);
}
}

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));
}
}

adding Strings to HashMap

I'm trying to put some Strings to a HashMap, but they wont add.
My code looks like this and I can't seem to understand why they won't add. Can someone help me and give me an explanation to what I'm doing wrong?
HashMap <String, String> akro = new HashMap <String, String>();
public void lesFil() {
try {
BufferedReader br = new BufferedReader(new FileReader("akronymer.txt"));
String line;
while((line = br.readLine()) != null) {
if(!line.contains(" ")) {
continue;
}
String[] linje = line.split("\\s+", 2);
String akronym = linje[0];
String betydning = linje[1];
// System.out.println(a + " || " + b);
akro.put(akronym, betydning);
}
} catch(Exception e) {
System.out.println("Feilen som ble fanget opp: " + e);
}
}
When I'm removing "//", both akronym and betydning prints out fine.
I tried to add this method to test the HashMap but nothing prints out and the size = 0
public void skrivUt() {
for(Map.Entry <String, String> entry : akro.entrySet()) {
System.out.print("Key: " + entry.getKey());
System.out.println(", Value: " + entry.getValue());
}
System.out.println("Antall akronymer: " + akro.size());
}
Part of the file I'm reading from(txt file):
...
CS Chip Select
CS Clear to Send
CS Code Segment
C/S Client/Server
...
Remember that a Map in Java maps one key to one value. In the sample data you provide, it seems that you have multiple values ("Chip Select", "Clear to Send", "Code Segment") for one key ("CS").
You can solve this by either picking a structure other than a Map, changing what you want to store, or changing the value of the Map to a List<String>.
For example:
List<String> values = akro.get(akronym);
if(values == null) {
values = new LinkedList<String>();
akro.put(akronym, values);
}
values.add(betydning);

Categories