Sunday, 2 July 2017

Write a program to sort a map by value.


Description:
Sort or order a HashMap or TreeSet or any map item by value. Write a comparator
which compares by value, not by key. Entry class might hleps you here.

Code:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.govindsblog.algos;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
 
public class OrderByValue {
 
    public static void main(String a[]){
        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("java", 20);
        map.put("C++", 45);
        map.put("govindsblog", 2);
        map.put("Unix", 67);
        map.put("MAC", 26);
        map.put("Why this kolavari", 93);
        Set<Entry<String, Integer>> set = map.entrySet();
        List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);
        Collections.sort( list, new Comparator<Map.Entry<String, Integer>>()
        {
            public int compare( Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2 )
            {
                return (o2.getValue()).compareTo( o1.getValue() );
            }
        } );
        for(Map.Entry<String, Integer> entry:list){
            System.out.println(entry.getKey()+" ==== "+entry.getValue());
        }
    }
}

Output:
Why this kolavari ==== 93
Unix ==== 67
C++ ==== 45
MAC ==== 26
java ==== 20
govindsblog==== 2

Saturday, 1 July 2017

Write a program to find common elements between two arrays.


Description:
Write a program to identify common elements or numbers between
two given arrays. You should not use any inbuilt methods are list to
find common values.

Code:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.govindsblog.algos;
 
public class CommonElementsInArray {
 
    public static void main(String a[]){
        int[] arr1 = {4,7,3,9,2};
        int[] arr2 = {3,2,12,9,40,32,4};
        for(int i=0;i<arr1.length;i++){
            for(int j=0;j<arr2.length;j++){
                if(arr1[i]==arr2[j]){
                    System.out.println(arr1[i]);
                }
            }
        }
    }
}

Output:
4
3
9
2