Wednesday, October 7, 2015

java - How to iterate through a HashMap

MainActivity.java

package com.cfsuman.me.javaexamples;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Window;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


public class MainActivity extends AppCompatActivity {
    private String mTitle = "Java - How to iterate through a HashMap";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_ACTION_BAR);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getSupportActionBar().setTitle(mTitle);
        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.RED));

        // Get widget reference from XML layout
        RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
        TextView tv = (TextView) findViewById(R.id.tv);

        // Empty the TextView
        tv.setText("");

        // Initializing a new HashMap
        HashMap<String, String> colors = new HashMap<>();
        // Put some key value pairs to HashMap
        colors.put("Red", "#FF0000");
        colors.put("Green", "#008000");
        colors.put("Blue", "#0000FF");

        // Iterate through the HashMap
        Iterator itr = colors.entrySet().iterator();
        tv.setText(tv.getText()+"Iterate over a HashMap");
        while(itr.hasNext()){
            Map.Entry pair = (Map.Entry) itr.next();
            tv.setText(tv.getText() + "\n" + pair.getKey() + " : " + pair.getValue());
            //iterator.remove();
        }

        // Another way to iterate through the HashMap
        tv.setText(tv.getText()+"\n\nAnother way to iterate over a HashMap");
        for(Map.Entry<String,String > entry : colors.entrySet()){
            tv.setText(tv.getText() + "\n" + entry.getKey() + " : " + entry.getValue());
        }

        // Another way to iterate over HashMap keys and get values also
        tv.setText(tv.getText()+"\n\nAnother way to iterate over a HashMap");
        for(String key : colors.keySet()){
            tv.setText(tv.getText() + "\n" + key + " : " + colors.get(key));
        }

        // Iterate over HashMap keys only
        tv.setText(tv.getText()+"\n\nIterate over HashMap keys only");
        for(String key : colors.keySet()){
            tv.setText(tv.getText() + "\n" + key);
        }

        // Iterate over HashMap values only
        tv.setText(tv.getText()+"\n\nIterate over HashMap values only");
        for(String value : colors.values()){
            tv.setText(tv.getText() + "\n" + value);
        }
    }
}
More android examples