Is that right way to iterate LinkedHashMap? - java

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

Related

Getting key value for Hashmap with If condition

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!");
}
...

Iterate Map in Java

Entry which needs to compare with the List and get the value from Map which is not there is the List.
for (Map.Entry<String, Object> entry : itemObj.entrySet())
{
System.out.println(entry.getKey());
for (ItemProcessVO processVO : itemDetails2){
if (entry.getKey().equalsIgnoreCase(processVO.getAccount())){
String account = processVO.getAccount();
lstAccVO.add(account);
}
}
}
This is the code i have used.I have Map of entry.getKey() has 6 Values while itemDetail2 has only 5 elements.I need to display only the missing account after comparing.
Simply add an else-statement to your if clause that stores that account in a local variable. Then after your for loops you can do whatever with that.
Hint: you can use loop over Map#keySet() instead of Map#entrySet() and bypass the entries that way.
In the provided example you compared the key with the account, simply use the else- statement to find the missingAccounts to iterate after this loop over them.
List<ItemProcessVO> missingAccounts= new ArrayList<>();
for (Map.Entry<String, Object> entry : itemObj.entrySet())
{
System.out.println(entry.getKey());
for (ItemProcessVO processVO : itemDetails2){
if (entry.getKey().equalsIgnoreCase(processVO.getAccount())){
String account = processVO.getAccount();
lstAccVO.add(account);
}else{
missingAccounts.add(account)
}
}
}
Below code should do the trick. It uses case insensitive comparison and prints remaining keys in the end, more explanation is in comments:
public static void main(String[] args) throws IOException {
Map<String, Object> itemObj = new HashMap<>(); //Your Map
List<ItemProcessVO> itemDetails2 = new ArrayList<>();// Your list
//First, get all the keys of the map
Set<String> keys = new HashSet<>(itemObj.keySet());
//Now, iterate through list and remove the matching items
for(ItemProcessVO processVO : itemDetails2){
String key = pop(keys, processVO.getAccount());
//If key is not null then remove it
if(null != key){
keys.remove(key);
}
}
//Now, iterate through remaining keys and print the values
for(String key : keys){
System.out.println("Missing value " + itemObj.get(key));
}
}
private static String pop(Set<String> set, String key){
if(null == set){
return null;
}else{
for(String element : set){
if(element.equalsIgnoreCase(key)){
return element;
}
}
}
}

Get Hashset Key

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public static void printNumWordsDiscovered( HashMap<String,Integer> vocab, HashSet<String> dictionary ) {
HashMap <String,Integer> Combine = new HashMap <String,Integer> ();
Iterator iterVoc = vocab.entrySet().iterator();
List<String> Dic = new ArrayList<String>();
int i = 0;
double actual = 0.0;
double token = 0.0;
while(iterVoc.hasNext()){
Map.Entry iterVocE = (Map.Entry)iterVoc.next();
if (dictionary.contains(iterVocE.getKey().toString())){
int Value = (int) iterVocE.getValue();
actual += 1;
token += Value;
Combine.put(iterVocE.getKey().toString(), Value);
}
}
for(String s: dictionary.KeySet()){
if (Combine.contains(dictionary.get(s).toString())){
System.out.println("Dicovered " + dictionary.get(s) + " ( count " + Combine.get(dictionary.get(s)) + " )");
}
}
}
I am trying to iterate through a HashSet and I get errors concerning my .get() method. How do you get a key in a HashSet?
A HashSet is backed by a HashMap. I want to mention this first, because what manouti said isn't exactly true. A HashSet does have a key; you just doesn't explicitly know about the key from outside the HashSet (or rather you don't call it the key, you call it the value outside of the HashSet).
In fact, the key in the internal HashMap is the value you use in HashSet#add(E). The code for HashSet#add(E):
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
where PRESENT is just a dummy object for the value:
private static final Object PRESENT = new Object();
What you want to do, is call the iterator for HashSet to iterate over all the keys. Per the java.util.HashSet#iterator documentation:
Returns an iterator over the elements in this set. The elements are returned in no particular order.
So this is the equivalent of getting the internal HashMap, getting the HashMap#keySet, and then getting an iterator over that. Not that it matters, but that is exactly how the internal code of HashSet actually does it:
public Iterator<E> iterator() {
return map.keySet().iterator();
}
So that might be a little more explanation than you were looking for, but to your issue:
There is no HashSet#get function, there is no HashSet#KeySet function, there is no HashMap#contains function so I recommend you read through the HashSet documentation at http://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html and HashMap documentation http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html before going any further. When in doubt, read the documentation. In Java you have the unique benefit of dealing with an API that is very, very well documented. If you choose not to use it, then its wasted.
In order to "get" anything out of a HashSet you have to have the object that results in the same hashCode anyway...so I'm not sure I quite understand the logic for what you are doing. In other words, if you already have the object, you don't need to get it from the HashSet.
Anyway, the last 6 lines of your code can be changed to this:
for(String s: dictionary.iterator()){
if (Combine.containsKey(s)){
System.out.println("Dicovered " + s + " ( count " + Combine.get(s) + " )");
}
}
You can use Iterator of HashSet.
Iterator it = dictionary.iterator();
String element;
while ( it.hasNext() ) {
element = ( String ) it.next();
if ( Combine.contains(element) ){
System.out.println("Dicovered " + element + " ( count " + Combine.get(element) + " )");
}
}
Iterate over HashSet by using iterator method which returns Iterator.
Use Iterator Pattern instead of:
for(String s: dictionary.KeySet()){
if (Combine.contains(dictionary.get(s).toString())){
System.out.println("Dicovered " + dictionary.get(s) + " ( count " + Combine.get(dictionary.get(s)) + " )");
}
}
Good luck!

JAVA Iterateing through Hasmap with list

I need iterate through hashmap and get key value which should be a string and all values within that key which is a list of strings that have strings?
Psuedo code
static HashMap<String, List<String>> vertices = new HashMap<String, List<String>>();
for (int i = 0; i < vertices.size(); i++)
{
String key = vertices.getKey at first postions;
for (int x = 0; x < size of sublist of the particular key; x++)
{
String value = vertices key sublist.get value of sublist at (i);
}
}
You can't iterate over HashMap directly, as there is no numeric index of values within HashMap. Instead key values are used, in your case of type String. Therefore the values don't have a particular order. However, if you want, you can construct a set of entries and iterate over that, using vertices.entrySet().
for (Entry<String, List<String>> item : vertices.entrySet()) {
System.out.println("Vertex: " + item);
for (String subitem : item.getValue()) {
System.out.println(subitem);
}
}
Try vertices.keySet();
It gives a Set of all keys in the map. Use it in a for loop like below
for (String key : vertices.keySet()) {
for (String value : vertices.get(key)) {
//do stuff
}
}

Why do my array.size() give wrong value?

I have an instance of ArrayList named array.
When I parse some JSON data it will store it all in array.
When I do a System.out.println(array); it will list a long list of items, around 30, but when I write System.out.println(array.size); it will give the value one.
How come it only gives me the value 1 when the list contains at least 30 values?
My code for this:
public void setLocationName (String name) {
array = new ArrayList<String>();
array.add(name);
System.out.println(array); //This return a long list
System.out.println(array.size()); //But this only return the value 1
}
public String[] getLocationName() {
String tArray[] = null;
for (int i = 0; i < array.size(); i++){
System.out.println(i);
tArray = array.toArray(new String[i]);
}
return tArray;
}
}
The long list :
[Brunnsparken, Göteborg]
[Brunnsgatan, Göteborg]
[Brunnslyckan, Lerum]
[Brunnsbotorget, Göteborg]
[Brunnsnäs, Ulricehamn]
[Brunnshult, Mellerud]
[Brunnsdal, Skövde]
[Brunns skola, Ulricehamn]
[Brunnsgården, Kungälv]
[Brunns kyrka, Ulricehamn]
[Boråsparken, Borås]
[Stadsparken, Ulricehamn]
[Lysekilsparken, Lysekil]
[Mössebergsparken, Falköping]
[Dalaborgsparken, Vänersborg]
[Rösparken, Åmål]
[Lillhagsparken Norra, Göteborg]
[Lillhagsparken Södra, Göteborg]
[Sylte Ryrbäcksparken, Trollhättan]
[Skogstomtsparken, Borås]
[Svinesundsparken, Norge]
[Håjumsparken, Trollhättan]
[Eriksdalsparken, Bollebygd]
[Fridhemsparken, Lidköping]
My result will be that only one item from the list will be returned in the tArray but I wanna return the whole list.
How to solve this?
Java doesn't understand Json and basically what you're doing is add a string to an array
this.array.add(name); ---> add one value to the array, therefore the size is just one
you may need to use a specific Json library to parse the data in to an java arraylist.
regards
Look like you need to parse the String into pairs.
Looks to me like a Map might be the most appropriate structure to store the data in - I presume the first part from the value is unique.
Regex is probably the best approach to parsing the data:
public static void main(String[] args) {
final String data = "[Brunnsparken, Göteborg]\n"
+ "[Brunnsgatan, Göteborg]\n"
+ "[Brunnslyckan, Lerum]\n"
+ "[Brunnsbotorget, Göteborg]\n"
+ "[Brunnsnäs, Ulricehamn]\n"
+ "[Brunnshult, Mellerud]\n"
+ "[Brunnsdal, Skövde]\n"
+ "[Brunns skola, Ulricehamn]\n"
+ "[Brunnsgården, Kungälv]\n"
+ "[Brunns kyrka, Ulricehamn]\n"
+ "[Boråsparken, Borås]\n"
+ "[Stadsparken, Ulricehamn]\n"
+ "[Lysekilsparken, Lysekil]\n"
+ "[Mössebergsparken, Falköping]\n"
+ "[Dalaborgsparken, Vänersborg]\n"
+ "[Rösparken, Åmål]\n"
+ "[Lillhagsparken Norra, Göteborg]\n"
+ "[Lillhagsparken Södra, Göteborg]\n"
+ "[Sylte Ryrbäcksparken, Trollhättan]\n"
+ "[Skogstomtsparken, Borås]\n"
+ "[Svinesundsparken, Norge]\n"
+ "[Håjumsparken, Trollhättan]\n"
+ "[Eriksdalsparken, Bollebygd]\n"
+ "[Fridhemsparken, Lidköping]";
final Pattern pattern = Pattern.compile("\\[([^,]++),\\s++([^\\]]++)\\]");
final Matcher matcher = pattern.matcher(data);
final Map<String, String> items = new TreeMap<>();
while (matcher.find()) {
items.put(matcher.group(1), matcher.group(2));
}
for (final Entry<String, String> entry : items.entrySet()) {
System.out.println(entry);
}
}
Output from this:
Boråsparken=Borås
Brunns kyrka=Ulricehamn
Brunns skola=Ulricehamn
Brunnsbotorget=Göteborg
Brunnsdal=Skövde
Brunnsgatan=Göteborg
Brunnsgården=Kungälv
Brunnshult=Mellerud
Brunnslyckan=Lerum
Brunnsnäs=Ulricehamn
Brunnsparken=Göteborg
Dalaborgsparken=Vänersborg
Eriksdalsparken=Bollebygd
Fridhemsparken=Lidköping
Håjumsparken=Trollhättan
Lillhagsparken Norra=Göteborg
Lillhagsparken Södra=Göteborg
Lysekilsparken=Lysekil
Mössebergsparken=Falköping
Rösparken=Åmål
Skogstomtsparken=Borås
Stadsparken=Ulricehamn
Svinesundsparken=Norge
Sylte Ryrbäcksparken=Trollhättan
You can the access the items by looping (as above) or by getting values from the Map by key. The TreeMap I have used will sort the data by key, you can also use a LinkedHashMap to store the data in insertion order.
You could also store the items in a List of tuple like structures.
public void setLocationName (String name) {
array = new ArrayList<String>();
array.add(name);
System.out.println(array); //This return a long list
System.out.println(array.size()); //But this only return the value 1
}
You are creating a new ArrayList each time you call this method:
array = new ArrayList<String>();
You could just remove the above line, however I suggest you rename the method as this is no longer a setter and you are in fact now adding to an existing list each time you call this method.
I suggest what you want to do is build your List before parsing to the setter, perhaps using a foreach loop (I'm not sure what kind of object you are working with) and simplify your setter (setLocationName) to accomodate.
So it would become:
public void setLocationName(ArrayList<String> names)
{
this.array = names;
System.out.println(array); //This return a long list
System.out.println(array.size()); //But this only return the value 1
}

Categories

Resources