Thursday, August 5, 2021

How to sort an HashMap based on value

 
 

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class SortHashMapByValue {

	public static void main(String[] args) {

		HashMap<String,Integer> unsortMap = new HashMap<String, Integer>();
		unsortMap.put("Ram", 10);
		unsortMap.put("Syam", 50);
		unsortMap.put("Radhe", 5);
		unsortMap.put("Krishna", 80);
		unsortMap.put("Suneel", 20);
		
		System.out.println("Before sorting:");
		printMap(unsortMap);
        
		System.out.println("\n");
		System.out.println("Sorting sorting:");
		HashMap<String,Integer> sortedMap = (sortHashMap(unsortMap));
		printMap(sortedMap);
		
	}

	private static HashMap<String, Integer> sortHashMap(HashMap<String, Integer> unsortMap) {
		List<Entry<String, Integer>> list = new LinkedList<Map.Entry<String,Integer>>(unsortMap.entrySet());
		Collections.sort(list, new Comparator<Map.Entry<String,Integer>>() {

			@Override
			public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
				
				return o1.getValue().compareTo(o2.getValue());
			}
		});
		
		LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
		for (Entry<String, Integer> entry : list) {
			sortedMap.put(entry.getKey(), entry.getValue());
		}
		return sortedMap;
	}

	private static void printMap(HashMap<String, Integer> unsortMap) {
		
		for(Entry<String, Integer> entry : unsortMap.entrySet()) {
			
			System.out.println("The Key is :- "+entry.getKey()+" The Value is:- "+entry.getValue());
		}
	}

}

Output:-

Before sorting: The Key is :- Radhe The Value is:- 5 The Key is :- Krishna The Value is:- 80 The Key is :- Syam The Value is:- 50 The Key is :- Suneel The Value is:- 20 The Key is :- Ram The Value is:- 10 Sorting sorting: The Key is :- Radhe The Value is:- 5 The Key is :- Ram The Value is:- 10 The Key is :- Suneel The Value is:- 20 The Key is :- Syam The Value is:- 50 The Key is :- Krishna The Value is:- 80

How to reverse linked list without using inbuild function or extra loop

  
import java.util.LinkedList;

public class LinkedListReversePractice {

	public static void main(String[] args) {

		LinkedList<Integer> numbers = new LinkedList<Integer>();
		numbers.add(1);
		numbers.add(2);
		numbers.add(3);
		numbers.add(4);
		numbers.add(5);
		
		System.out.println("LinkedList before reversion:- "+numbers);
		
		numbers = reverseLinkedList(numbers);
		System.out.println("LinkedList after reversion:- "+numbers);
		
	}

	private static LinkedList<Integer> reverseLinkedList(LinkedList<Integer> numbers) {
		
		for(int i = 0; i< numbers.size()/2; i++) {
			 
			int temp = numbers.get(i);
			numbers.set(i, numbers.get(numbers.size()-1-i));
			numbers.set(numbers.size()-1-i, temp);
			
		}
		return numbers;
	}
	
}

Output:-

LinkedList before reversion:- [1, 2, 3, 4, 5] LinkedList after reversion:- [5, 4, 3, 2, 1]

How to find prime numbers from 1 to 100


public class PrimeNumber1To100 {

	public static void main(String[] args) {

		System.out.println("Prime numbers from 1 to 100 are :");

		for(int i=1;i<=100;i++) {
			
			int counter=0;
			for(int num = i;num>=1;num--) {
				
				if(i%num == 0) {
					
					counter++;
				}
			}
			if(counter == 2) {
				System.out.print(i+" ");
			}
		}
	}

}

Output:-

Prime numbers from 1 to 100 are : 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

Least repeated Item in the Integer Array

  
  
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class LeastRepeatedNumber {

	public static void main(String[] args) {

		int[] array1 = {1,1,3,2,3,1,4,2,2};
		System.out.println("Least Repeated Number is : "+findLeastRepatedNumber(array1));

	}
	public static Integer findLeastRepatedNumber(int ...array) {
		Integer leastRepatedCount=0;
		Map<nteger,Integer> map = new HashMap<>();
		Integer leastRepeatedItem=null;
		for(int i:array) {

			if(map.containsKey(i)) {
				int counter = map.get(i)+1;
				map.put(i, counter);
			}else {
				map.put(i,1);
			}

		}

		for(Entry<Integer, Integer> entry : map.entrySet()) {

			int v = entry.getValue();
			int k = entry.getKey();
			if(v>1) {

				if(leastRepatedCount==0 || v<leastRepatedCount) {
					leastRepatedCount = v;
					leastRepeatedItem = k;
				}

			}

		}
		return leastRepeatedItem;
	}
}


Output:-

Least Repeated Number is : 3

Thursday, March 18, 2021

Common elements in two sorted arrays



import java.util.ArrayList;
import java.util.Arrays;

public class CommonNumbers {

	public static void main(String[] args) {
          int[] array1A = {1, 3, 4, 6, 7, 9};
          int[] array2A = {1, 2, 4, 5, 9, 10};
          Integer[] com = common(array1A,array2A);
          for(int i : com) {
              System.out.println(i);
          }

	}

	public static Integer[] common(int array1[], int array2[]) {
		
		int p1=0,p2=0;
		ArrayList<Integer> list = new ArrayList<>();
		while(p1<array1.length && p2 < array2.length) {
			
			if(array1[p1]  == array2[p2]) {
				list.add(array1[p1]);
				p1++;
				p2++;
			}else if(array1[p1] > array2[p2]) {
				p2++;
			}else {
				p1++;
			}
		}
		Integer[] common = new Integer[list.size()];
		return list.toArray(common);
	}
}

Output:-

1 4 9

Wednesday, March 17, 2021

How to find pair of two numbers that's multiply equals to Key

  

    import java.util.ArrayList;

    public class FindPair {

        public static void main(String[] args) {
            int arr[] = {1,2,4,6,3,5}; 
            int key = 20; 
            findPair(arr,key);


        }

        private static void findPair(int[] arr, int key) {
            ArrayList<Integer> numbers = new ArrayList<>();
            boolean status = false;
            for(int num : arr) {

                int anotherNumber = (key/num);
                if(numbers.contains(anotherNumber) && (anotherNumber*num) == key) {
                    status=true;
                    System.out.println("Pair Found: "+"( "+anotherNumber+", "+ num+" )"); 
                }
                numbers.add(num);
            }
            if(!status)
                System.out.print("No such pair"); 

        }

    }

Output:-

Pair Found:- (4,5)

Most Frequently Occurring Item in an Array

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

  public class MostOccuranceNumber {

      public static void main(String[] args) {

          int[] array1 = {1,2,4,1,3,6,1};
          System.out.println(mostOccurance(array1));

      }
      public static Integer mostOccurance(int ...array) {
          Integer mostCount=0;
          Map<Integer,Integer> map = new HashMap<>();
          Integer mostItem=null;
          for(int i:array) {

              if(map.containsKey(i)) {
                  int counter = map.get(i)+1;
                  map.put(i, counter);
              }else {
                  map.put(i,1);
              }
              if(map.get(i) > mostCount) {
                  mostCount = map.get(i);
                  mostItem = i;
              }
          }
          return mostItem;
      }
  }

Output:-

1

How to sort an HashMap based on value

import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java....