For loop string in java

1. For loop string in java

for (char c : string1.toCharArray()) {

}

String s = "xyz";
for(int i = 0; i < s.length(); i++)
{
   char c = s.charAt(i);
}

2. hash map size

hashmap.size()

3. hash map compare keys and values

Make an equals check on the keySet() of both HashMaps.

NOTE:

If your Map contains String keys then it is no problem, but if your Map contains objA type keys then you need to make sure that your class objA implements equals().

You can use

   if(mapA.keySet().equals(mapB.keySet())){
        System.out.println("Map are same");
    }else {
        System.out.println("Map are not same");
    }

Here it will check whether keySet of two HashMap are same or not.

EX:

   Map<String, String> mapA = new HashMap<String, String>();
    mapA.put("A", "1");
    mapA.put("B", "2");

    Map<String, String> mapB = new HashMap<String, String>();
    mapB.put("B", "3");
    mapB.put("A", "1");

    if(mapA.keySet().equals(mapB.keySet())){
        System.out.println("Maps are same");
    }else {
        System.out.println("Maps are not same");
    }

Out put

  Maps are same

 

        if (hash1.size() == hash2.size()) {

            // compare keys

            if (hash1.keySet().equals(hash2.keySet())) {

                // compare values

                Set<String> set = hash1.keySet();

                String[] arr = set.toArray(new String[set.size()]);

                for (String str : arr) {

                    if (hash1.get(str) == hash2.get(str)) {

                        continue;

                    } else {

                        return false;

                    }

                }

                

                return true;

            } else

                return false;

        } else {

            return false;

        }

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s