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
Related
I am storing the key = "name" and value = "state" in a Hashmap.
Now once I get the hashmap with all keys and values
I want to iterate the hashmap and have to check whether the state(value) is running or not
If the state is not running I want to print the name of that server(which is key in hashmap)
Code I am using is
for(int z=0; z<=containsAll.size();z++) {
if(!containsAll.containsValue("Running")) {
System.out.println(containsAll.keySet());
}
}
Here contains all is the name of my Hashmap. Can someone help me in getting the name for which state is not running
if (containsAll != null) {
containsAll.forEach((k, v) -> {
if (v != null && !v.contains("Running")) {
System.out.println(k);
}
});
}
Iterate every key-value pair of the map, and if the value don't contain "Running", print the key.
you can traverse the map using entrySet()
Iterator it = containsAll.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
if(!((pair.getValue()).equals("Running")){
System.out.println(pair.getKey()+" is not running");
}
it.remove();
}
I'd make a new class to represent a server and within this class I'd define the state as boolean and the name as string. Furthermore I'd use a list of those Objects to iterate through and do something like this(given, the list is typed List):
...
for(MyServerObject mso : containsAll){
if(mso.isRunning())
System.out.println(mso.getName());
}
...
If this is not possible as you get the Map as is from somewhere else try the following (I'm assuming your Map is typed Map<String,String>):
...
Iterator<Map.Entry<String, String>> iterator = containsAll.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
if("Running".equalsIgnoreCase(entry.getValue())
System.out.println(entry.getKey() + " is running!");
}
...
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
});
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 have a List with about 20,000,000 entries. About 5,000,000 entries are unique. I need to iterate over my List, identify unique entries, and assign each an integer between 0 and 5,000,000.
Currently, I sequentially add each entry to a TreeSet, then figure out where it went using .headSet(). I imagine this is suboptimal.
while((nextline = wholefile.listIterator().next()) != null){
//sorted, unique, addition
keywords.add(nextline);
//hmmm, get index of element in TreeSet?
k_j = keywords.headSet(nextline).size();
}
Is there a way to get the location when I call .add() ?
I would simply use a counter and HashMap<Keyword, Integer>. For each keyword in the list, get its position from the map. If you get null, put the keyword in the map with the current counter value as value, and increment the counter.
I would do as follows:
Count the objects by populating a Map<YourObject, Integer>.
Go through this map and assign a sequence number to each key which maps to the value 1.
In code...
List<String> keywords = Arrays.asList("a", "b", "c", "a");
Map<String, Integer> counts = new HashMap<String, Integer>();
for (String str : keywords) {
if (!counts.containsKey(str))
counts.put(str, 0);
counts.put(str, counts.get(str) + 1);
}
int seq = 0;
for (String keyword : counts.keySet())
if (counts.get(keyword) == 1) // is unique?
System.out.println(keyword + " -> " + seq++); // assign id.
I am trying to iterate LinkedHashMap but its not coming in right i have attached the code below
for (int g = 0; g < list_Fields.size(); g++) {
System.out.println("Hello ListOFFields:" + list_Fields.get(g));
row = (LinkedHashMap) list_Fields.get(g);
Iterator ie = row.keySet().iterator();
while (ie.hasNext()) {
String colName = ie.next().toString();
System.out.println("<TD>" + colName + "</TD>");
}
}
I am not sure why it is made so clumsy. Here is what we normally done when iterating collections in Java (as u r using LinkedHashMap, I assume you are using Java 5+)
// assume listField is Collection<Map<String,ANYTHING>>
for (Map<String,ANYTHING> row : listFields) {
for (String ie : row.keySet()) {
System.out.println("<TD>" + ie +"</TD>");
}
}
Modify it the way you want print statements
If you just want Keys then use keySet() instead of entrySet()
Here you go:
public static List<LinkedHashMap<Object,Object>> dummy = new ArrayList<LinkedHashMap<Object,Object>>();
public static void display(){
for(LinkedHashMap<Object,Object> map : dummy){
for (Map.Entry<Object, Object> entry : map.entrySet()) {
Object key = entry.getKey();
Object value = entry.getValue();
//Your code
}
}
}
I guess it should be like this:
for (Entry entry: map.entrySet())
{
System.out.println(entry.getKey() + " = " + entry.getValue());
}
You iterate over list of fields and inside of the iteration you iterate over collections of values. You will end-up with a table with row-per field with mixed amount of in it.
If you want to get a simple table - change order of you fields/data collections and switch you iteration order that you iterate on rows first and on fields second:
List<Map<String,String>> rows = ...
for ( Map data : rows ) {
System.out.println("<TR>");
for ( String fld : list_Fields ) {
System.out.println("<TD>" + data.get(fld) + "</TD>");
}
System.out.println("</TR>");
}