so basically, I'm trying to parse through each map entry of a HashMap while also reading each string value in the String array. I will then use each of those string values in the array as parameters for specific methods. Now, I know how to parse through each map entry, it's just the iterating through the string array in the map that's confusing me. Any advice?
My code:
HashMap<String,String[]> roomSite = new HashMap<String, String[]>();
Set set = roomSite.entrySet();
Iterator<Map.Entry<String, String[]>> iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry mentry = (Map.Entry)iterator.next();
System.out.print("key is: "+ mentry.getKey() + " & Value is: ");
System.out.println(Arrays.deepToString((String[]) mentry.getValue()));
}
Output:
key is: 0 & Value is: [wall, d0, wall, wall]
key is: 1 & Value is: [d0, wall, d1, wall]
key is: 2 & Value is: [wall, wall, wall, d1]
You already have the String array, just assign it to a variable:
String[] stringArray = (String[]) mentry.getValue();
for (String str : stringArray){
// process str
}
Solution using Java 8 stream feature
HashMap<String,String[]> roomSite = new HashMap<>();
roomSite.put("1",new String[]{"Hello","World"});
roomSite.put("2",new String[]{"India","Germany"});
//This is to print all value for given key but if you want process for each key with all value then put ur logic into forEach
roomSite.entrySet().stream().map(entry -> "key is: "+entry.getKey() + " & Value is: " + Arrays.stream(entry.getValue())
.collect(Collectors.joining(","))).forEach(System.out::println);
//This logic emits entry for key and value from array, basically you will have pair of key and value which can be used for processing
roomSite.entrySet().stream().flatMap(entry-> Arrays.stream(entry.getValue()).map(value->new AbstractMap.SimpleEntry<>(entry.getKey(),value))).forEach(simpleEntry-> {
final String key= simpleEntry.getKey();
final String value= simpleEntry.getValue();
System.out.println("Key : "+ key+" , value : "+ value);
//process ur logic
});
Related
I have a HashMap with String key and String value. I want to get an item from list, I tried to give key and wanted to get value but it gives an error.
The following example how can I get "both" value with give the key "blazer"?
HashMap<String,String> upper = new HashMap<>();
upper.put("shoulder","both");
upper.put("blazer","both");
if(upper.get(upper.get("blazer"))) {} //gives an "incompatible types" error.
//Error: Required: boolean Found: java.lang.String
Understand that upper.get(key) will not return a boolean value. You have defined your HashMap as follows:
HashMap<String,String> upper = new HashMap<>();
This means that both the key and value will be of type String. Thus, providing a valid key the the get() method will return a String:
String myValue = upper.get("blazer");
If you wish to check if a key is available before you attempt to read the value you can use the method containsKey() with will return a boolean value indicating whether the HashMap contains an entry with the given key:
if(upper.containsKey("blazer")){
String myValue = upper.get("blazer");
Log.e(TAG, "Yes blazer is available : " + myValue);
}
else{
Log.e(TAG, "No blazer is available!");
}
You can also iterate through the available keys like this:
Set<String> set = map.keySet();
for(String s : set){
Log.e(TAG, "Map key = " + s + " value = " + map.get(s));
}
They way you have it there upper.get(upper.get("blazer")); would just return null.
You're passing in upper.get("blazer") (which would return "both") to your outer upper.get. Since you have no "both" key stored in your map, it returns null.
Should be:
upper.get("blazer");
I want to print all the keys and all the attributes of an object from a multiMap.
The same key can have different objects.
I have created the multiMap with the following code:
Multimap<Integer,Country> country=ArrayListMultimap.create();
My Class country is:
class Country {
String country;
int population;
}
How can i retrieve all the object attributes from it:
With HashMap i was using the following code:
for (Map.Entry p : country.entrySet()) {
Country country=(Country)p.getValue();
nameCountry=country.country;
population=country.population;
}
Use keySet() to avoid repetitions, keys() if you want repetitions. Then get the country instance via get(..)
Use almost the same but instead of entrySet() use entries():
for (Map.Entry<Integer, Country> p : country.entries()) {
Country country=(Country)p.getValue();
nameCountry=country.country;
population=country.population;
}
You can use keySet to get unique keys and then get the collection for the key.
for (Integer key : countries.keySet()) {
Collection<Country> collection = countries.get(key);
for (Country country : collection)
{
String name = country.country;
int poplulation = country.population;
}
}
Give my example of using it
Multimap<String, String> NameList = ArrayListMultimap.create();
NameList.put("david", "1");
NameList.put("david", "2");
NameList.put("jonathan", "4");
NameList.put("david", "2");
Collection<String> values = NameList.get("david");
System.out.println("all david list: " + values);
Iterator iterator = values.iterator();
System.out.println("first element: " + iterator.next());
System.out.println("second element: " + iterator.next());
System.out.println("third element: " + iterator.next());
System.out.println("number of david elements "+NameList.get("david").size());
the printed result will be
all david list: [1, 2, 2]
first element: 1
second element: 2
third element: 2
number of david elements 3
import java.util.HashMap;
import java.util.TreeMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Set;
public class Maps {
public static void main(String[] args) {
Map mapA = new HashMap();
Map mapB = new TreeMap();
mapA.put("key1", "element 1");
mapA.put("key2", "element 2");
mapA.put("key3", "element 3");
// The three put() calls maps a string value to a string key. You can then
// obtain the value using the key. To do that you use the get() method like this:
String element1 = (String) mapA.get("key1");
// why do I need the type cast on the right?
System.out.println(element1);
//Another examples with maps
Map vehicles = new HashMap();
vehicles.put("BMW", 5);
vehicles.put("Mercedes", 3);
vehicles.put("Audi", 4);
vehicles.put("Ford", 10);
System.out.println("Total vehicles: " + vehicles.size());
for(String key: vehicles.keySet())
System.out.println(key + " - " + vehicles.get(key));
System.out.println();
String searchKey = "Audi";
if (vehicles.containsKey(searchKey))
System.out.println("Found total " + vehicles.get(searchKey) + " "
+ searchKey + " cars!\n");
// clears vehicles
vehicles.clear();
//should equal to 0 now
System.out.println("Vehicle now contains this many vehicles :" + vehicles.size());
// Lets iterate through the keys of this map:
Iterator iterator = mapA.keySet().iterator();
System.out.println(iterator); // How to inspect this? Is it a kind of map?
Map mapC = new HashMap();
while(iterator.hasNext()){
Object key = iterator.next();
Object value = mapA.get(key);
mapC.put(key,value);
} // Is there a better way to take the contents of the iterator and put them in a new map?
System.out.println(mapC);
//create a new hashmap
HashMap hm = new HashMap();
// put elements to the map
hm.put("Zara", new Double(3434.34));
hm.put("Mahnaz", new Double(123.22));
hm.put("Ayan", new Double(1378.00));
hm.put("Daisy", new Double(99.22));
hm.put("Qadir", new Double(-19.08));
//get a set of the entries
// The entrySet( ) method declared by the Map interface returns a Set containing the
// map entries.
Set set = hm.entrySet();
// get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.println(i.getClass()); // get the class of i
System.out.println(i instanceof Iterator); // checks to see if i is of class Iterator
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into Zara's account
double balance = ((Double)hm.get("Zara")).doubleValue();
hm.put("Zara", new Double(balance + 1000));
System.out.println("Zara's new balance: " +
hm.get("Zara"));
}
}
This is my error:
Maps.java:53: error: incompatible types: Object cannot be converted to
String
for(String key: vehicles.keySet())
My questions are
Why is that error occurring? Why is an object trying to be converted to a string? I thought I had put strings as keys into the vehicles HashMap. What is going on?
Why is the typecast needed in the line:
String element1 = (String) mapA.get("key1");
vehicles.keySet() returns a collection of Object, not String. Just because you put strings in as the keys, the API doesn't change.
One approach would be:
for(Object keyObj: vehicles.keySet())
{
String key = keyObj.toString(); // or cast to (String)
Same issue - get() returns an Object. Just because you used a string, the API is still just an object. Again either cast or use toString.
As has been hinted in various comments, if you use generics the compiler has a much better idea of "what types are where". If you define your map like Map<String,String> mapA = new HashMap<String, String>(); then your original code may work because the compiler knows what the data types in the map are.
I have two collections where both the keys and the values are strings. I need the collections to be ordered, so I decided to use "TreeMap" to keep the ordering.
I want to:
1) print out the two collections, 'garList' and 'noGarList', respectively;
2) compare each and every element of the first collection with each and every element of the second collection;
3) remove from the first collection ('garList') those elements that appear in the second collection ('noGarList') as well.
I wrote the following code to do these 3 tasks:
public class TryTask_A_copy {
public static void main(String[] args) {
// First collection:
TreeMap<String, String> garList = new TreeMap<>();
// Second collection:
TreeMap<String, String> noGarList = new TreeMap<>();
// Fill the "Properties" obj for 'Gar':
garList.put("Gar_1", "rotura de lunas");
garList.put("Gar_2", "arbitraje de ley");
garList.put("Gar_3", "Adaptación del hogar");
// Fill the "Properties" obj for 'noGar':
noGarList.put("noGar_1", "rotura de lunas");
noGarList.put("noGar_2", "reembolso total");
noGarList.put("noGar_3", "Adaptación del coche");
// Get a set of the entries:
Set garSet = garList.entrySet();
Set noGarSet = noGarList.entrySet();
// Def strings needed for the comparison:
String strGar;
String strNoGar;
// Get an iterator:
Iterator i_gar = garSet.iterator();
Iterator i_noGar = noGarSet.iterator();
// Display 'Gar' elements:
while(i_gar.hasNext()){
String me_Gar = (String)i_gar.next(); // Exception in thread "main" java.lang.ClassCastException: java.util.TreeMap$Entry cannot be cast to java.lang.String
strGar = (String) i_gar.next();
System.out.println(strGar + " : " + garList.get(strGar) + ".");
}
System.out.println();
// Display 'noGar' elements:
while(i_noGar.hasNext()){
String me_noGar = (String)i_noGar.next();
strNoGar = (String) i_noGar.next();
System.out.println(strNoGar + " : " + garList.get(strNoGar) + ".");
}
// Get new iterators:
Iterator itr_gar = garSet.iterator();
Iterator itr_noGar = noGarSet.iterator();
// Compare elements from 'Gar' list with elements from 'noGar' list
// and remove those elements from 'Gar' list that appear in 'noGar' list as well:
while(itr_gar.hasNext()){
strGar = (String) itr_gar.next();
while(itr_noGar.hasNext()){
String str1 = garList.get(strGar);
strNoGar = (String) itr_noGar.next();
String str2 = noGarList.get(strNoGar);
boolean result = str1.equalsIgnoreCase(str2);
System.out.println(strGar + " : " + str1 + ".");
System.out.println(strNoGar + " : " + str2 + ".");
System.out.println(result);
System.out.println();
// if an element appears in both lists, then remove this element from "Gar" list:
if(result != true){
} else {
Object garList_new = garList.remove(strGar);
System.out.println("Removed element: " + garList_new);
System.out.println();
}
}
itr_noGar = noGarSet.iterator();
}
}
}
But I get:
Exception in thread "main" java.lang.ClassCastException:
java.util.TreeMap$Entry cannot be cast to java.lang.String" at line 51
(see comments).
I understand that the elements of my two TreeMap objects are of "Map Entry" type and cannot be converted to "String" type, is that correct?
But then how can I get an ordered collection where both the keys and the values are Strings?
Writing something like garSet.removeAll(noGarSet) does not work because this would imply that both key AND value coincide. But in my case I have some of the values in the two collections coinciding while having different keys.
So I need a solution to the following: have an ordered collection where both keys and values are Strings and where values can be compared and removed.
Can you please help me out with this?
I'm a little unclear on just what you are trying to achieve but if you want to remove based on keys then just do:
garSet.removeAll(noGarSet);
Your code in general seems to be far more complex than it needs to be for what you are trying to achieve. For example to print all the Strings in the Map just do:
for (Entry<String, String> entry: garMap.entrySet()) {
System.out.println(entry.key() + " : " + entry.value() + ".");
}
If you do:
map1.keySet().removeAll(map2.keySet())
then that will remove all the duplicates based on key.
map1.values().removeAll(map2.values())
will remove all duplicates based on value.
map1.entryset().removeAll(map2.entrySet())
will remove all duplicates based on key/value pairs.
I am new to Java. I want to Parse the data which is in this Format
Apple;Mango;Orange:1234;Orange:1244;...;
There could be more than one "Orange" at any point of time. Numbers (1,2...) increase and accordingly as the "Orange".
Okay. After splitting it, Lets assume I have stored the first two data(Apple, Orange) in a variable(in setter) to return the same in the getter function. And now I want to add the value(1234,1244....etc) in the 'orange' thing into a variable to return it later. Before that i have to check how many oranges have come. For that, i know i have to use for loop. But don't know how to store the "Value" into a variable.
Please Help me guys.
String input = "Apple;Mango;Orange:1234;Orange:1244;...;"
String values[] = input.split(";");
String value1 = values[0];
String value2 = values[1];
Hashmap< String, ArrayList<String> > map = new HashMap<String, ArrayList<String>>();
for(int i = 2; i < values.length; i = i + 2){
String key = values[i];
String id = values[i+1];
if (map.get(key) == null){
map.put(key, new ArrayList<String>());
}
map.get(key).add(id);
}
//for any key s:
// get the values of s
map.get(s); // returns a list of all values added
// get the count of s
map.get(s).size(); // return the total number of values.
Let me try to rephrase the question by how I interpreted it and -- more importantly -- how it focuses on the input and output (expectations), not the actual implementation:
I need to parse the string
"Apple;Mango;Orange:1234;Orange:1244;...;"
in a way so I can retrieve the values associated (numbers after ':') with the fruits:
I should receive an empty list for both the Apple and Mango in the example, because they have no value;
I should receive a list of 1234, 1244 for Orange.
Of course your intuition of HashMap is right on the spot, but someone may always present a better solution if you don't get too involved with the specifics.
There are a few white spots left:
Should the fruits without values have a default value given?
Should the fruits without values be in the map at all?
How input errors should be handled?
How duplicate values should be handled?
Given this context, we can start writing code:
import java.util.*;
public class FruitMarker {
public static void main(String[] args) {
String input = "Apple;Mango;Orange:1234;Orange:1244";
// replace with parameter processing from 'args'
// avoid direct implementations in variable definitions
// also observe the naming referring to the function of the variable
Map<String, Collection<Integer>> fruitIds = new HashMap<String, Collection<Integer>>();
// iterate through items by splitting
for (String item : input.split(";")) {
String[] fruitAndId = item.split(":"); // this will return the same item in an array, if separator is not found
String fruitName = fruitAndId[0];
boolean hasValue = fruitAndId.length > 1;
Collection<Integer> values = fruitIds.get(fruitName);
// if we are accessing the key for the first time, we have to set its value
if (values == null) {
values = new ArrayList<Integer>(); // here I can use concrete implementation
fruitIds.put(fruitName, values); // be sure to put it back in the map
}
if (hasValue) {
int fruitValue = Integer.parseInt(fruitAndId[1]);
values.add(fruitValue);
}
}
// display the entries in table iteratively
for (Map.Entry<String, Collection<Integer>> entry : fruitIds.entrySet()) {
System.out.println(entry.getKey() + " => " + entry.getValue());
}
}
}
If you execute this code, you will get the following output:
Mango => []
Apple => []
Orange => [1234, 1244]