12
Mar

HashMap common usages for Strings

Map refresher
======================


============  map1.putAll(map2) ===============

for:	map1 = {a=1, b=1, c=1, d=1, e=1, f=1, g=1}
	map2 = {a=2, b=2, c=2, w=2, x=2, y=2, z=2}

## map1.putAll(map2);		//  if same keys are found -- the value will be overwritten by the map2's value

	o/p => {a=2, b=2, c=2, d=1, e=1, f=1, g=1, w=2, x=2, y=2, z=2}

============ map1.entrySet().retainAll(map2.entrySet() =================

for:	map1 = {a=1, b=1, c=1, d=1, e=1, f=1, g=1}
	map2 = {a=1, b=1, c=1, w=1, x=1, y=1, z=1}

## map1.entrySet().retainAll(map2.entrySet());	//  if same key/value pair is found, retains all common K,V pair (between two maps)

	o/p => {a=1, b=1, c=1}


============ map1.entrySet().removeAll(map2.entrySet()) =================

for:	map1 = {a=1, b=1, c=1, d=1, e=1, f=1, g=1}
	map2 = {a=1, b=1, c=1, w=1, x=1, y=1, z=1}

## map1.entrySet().removeAll(map2.entrySet());	// if same K/V pair is found, remove all common Keys from map1

	o/p => {d=1, e=1, f=1, g=1}



============ map.forEach() =============

		BiConsumer<? super Character,? super Number> myBiConsumer = (K,V)-> {
			System.out.println("Key "+ K+" :: "+"Value "+V);  // instead of this you can manipulate K,V here

		};
		
		map1.forEach(myBiConsumer);

	o/p => 	Key a :: Value 1
		Key b :: Value 1

============== map.replaceAll() =========

	// Define a Bifunction as per K,V types of Map to update all Values of given map
	BiFunction<? super Character, ? super Number, ? extends Number> biConsumer = ((key, value) -> {
		// Process here for new value for entire map 
		value=99;
		return value;
	});

	map1.replaceAll(biConsumer);
	System.out.println(map1);

	o/p => 	{a=1, b=1, c=1 ... g=1}



============== map.merge ================

		// Bifunction updates Value of specific Key 
		BiFunction<? super Number, ? super Number, ? extends Number> biConsumer = ((key, value) -> {
			// Process here for K,V pair 
				value=99;
			return value;
			});

		Character k = "a".charAt(0);
		Number v = 1;
		map1.merge(k, v,biConsumer);
		System.out.println(map1);		//{a=99, b=1, c=1, d=1, e=1, ....}  (if Key a's value is null or any other value in map1)


============ map.computeIfPresent() ====================

		//Bifunction to compute key's value if present in Map
		BiFunction<? super Character,? super Number,? extends Number> myBiConsumer = (K,V)-> {
			K = "Z".charAt(0);
			V = 99;
			return V;
		};
		map1.computeIfPresent("a".charAt(0), myBiConsumer);     {a=99, b=1, c=1, d=1, e=1, f=1, g=1}



==============  Practice problems  ============

Create a map to store "Character count" for given string
==========================================================

		String address = "Jackiechan";
		address = address.replaceAll("\\s", "");

		Map<Character, Integer> map = new LinkedHashMap<>();

		for (Character c : address.toCharArray()) {
			map.put(c, map.containsKey(c) ? (map.get(c) + 1) : 1);
		}

		System.out.println("Original Map and count of chars => " + map);


Find first non-repeating character in given string
=====================================================

		//First non-repeating character
		Character fnr=null;
		for(Map.Entry<Character, Integer> es : map.entrySet()) {
			if(es.getValue()==1) {
				fnr=es.getKey();
				break;
			}				
		}
		System.out.println("First unique character => "+fnr);

		//Last non-repeating character
		Character lnr=null;
		for(Map.Entry<Character, Integer> es : map.entrySet()) {
			if(es.getValue()==1) {
				lnr=es.getKey();
			}				
		}
		System.out.println("First unique character => "+lnr);


Sort given HashMap based on Values
=====================================

		// Sort map on Values
		List<Map.Entry<Character, Integer>> list = new LinkedList<Map.Entry<Character, Integer>>(map.entrySet());

		Collections.sort(list, new Comparator<Map.Entry<Character, Integer>>() {
			public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2) {
				return (o1.getValue()).compareTo(o2.getValue());
			}
		});

		// put data from sorted list to hashmap
		HashMap<Character, Integer> temp = new LinkedHashMap<Character, Integer>();
		for (Map.Entry<Character, Integer> aa : list) {
			temp.put(aa.getKey(), aa.getValue());
		}
		
		System.out.println("Sorted Map (by Values) => "+temp);



Sort given HashMap based on Keys
==================================

		// Sort map on Keys
		List<Map.Entry<Character, Integer>> listKeys = new LinkedList<Map.Entry<Character, Integer>>(map.entrySet());

		Collections.sort(listKeys, new Comparator<Map.Entry<Character, Integer>>() {
			public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2) {
				return (o1.getKey()).compareTo(o2.getKey());
			}
		});

		// put data from sorted listKeys to hashmap
		HashMap<Character, Integer> temp = new LinkedHashMap<Character, Integer>();
		for (Map.Entry<Character, Integer> aa : listKeys) {
			temp.put(aa.getKey(), aa.getValue());
		}
		
		map.clear();
		map.putAll(temp);

		System.out.println("Sorted Map (by Keys) => "+map);


Find the frequency of 7rd largest occuring value from given string
====================================================================


	// Find the 2nd, 3rd or nth largest Key/value in HashMap

	//# Step 1:  Sort map on Values
		List<Map.Entry<Character, Integer>> list = new LinkedList<Map.Entry<Character, Integer>>(map.entrySet());

		Collections.sort(list, new Comparator<Map.Entry<Character, Integer>>() {
			public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2) {
				return (o1.getValue()).compareTo(o2.getValue());
			}
		});

	//# Step 2:  put data from sorted list to hashmap
		HashMap<Character, Integer> temp = new LinkedHashMap<Character, Integer>();
		for (Map.Entry<Character, Integer> aa : list) {
			temp.put(aa.getKey(), aa.getValue());
		}
			map.clear();
		map.putAll(temp);
		temp.clear();
		System.out.println("Sorted Map (by Values) => " + map);
		
	//# Step 3:  Store sorted keys/values in arrays
		Integer[] sortedArrVals = new Integer[map.size()];
		Character[] sortedArrKeys = new Character[map.size()];
		int index =0;
		for (Map.Entry<Character, Integer> aa : map.entrySet()) {
			sortedArrVals[index]=aa.getValue();
			sortedArrKeys[index]=aa.getKey();
			index++;
		}

		System.out.println("7rd largest occuring value from map "+sortedArrKeys[7]+"::"+sortedArrVals[7]);



Find the Nth smallest Key/Value in given String
=================================================


		// Reverse sort map on Keys
		List<Map.Entry<Character, Integer>> list = new LinkedList<Map.Entry<Character, Integer>>(map.entrySet());

		Collections.sort(list, new Comparator<Map.Entry<Character, Integer>>() {
			public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2) {
				return (o2.getKey().compareTo(o1.getKey()));
			}
		});

		// put data from sorted list to hashmap
		HashMap<Character, Integer> temp = new LinkedHashMap<Character, Integer>();
		for (Map.Entry<Character, Integer> aa : list) {
			temp.put(aa.getKey(), aa.getValue());
		}
		map.clear();
		map.putAll(temp);
		temp.clear();
		System.out.println("Sorted Map (by Values) => " + map);
		
		Integer[] sortedArrVals = new Integer[map.size()];
		Character[] sortedArrKeys = new Character[map.size()];
		int index =0;
		for (Map.Entry<Character, Integer> aa : map.entrySet()) {
			sortedArrVals[index]=aa.getValue();
			sortedArrKeys[index]=aa.getKey();
			index++;
		}

		System.out.println("3rd smallest K/V pair in map "+sortedArrKeys[3]+"::"+sortedArrVals[3]);