Saturday, 2 July 2016

Map Sort By Value Example

Q:  Write a Program to Sort a Map By It's  Value?

Ans: Using Collections.sort () method and Comparator We can Solve It.

Example:

package com.test.practice;

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.Map.Entry;
import java.util.Set;


public class MapSortByValue {

public static void main(String[] args) {

Map<String,Integer> mapObj = new HashMap<String,Integer>();

mapObj.put("Sunil", 50);
mapObj.put("Kumar", 60);
mapObj.put("Jaydeb", 45);
mapObj.put("Rana", 70);
mapObj.put("Sita",65);





Set<Entry<String,Integer>> setObj = mapObj.entrySet();
                 // Map---> EntrySet

List <Entry<String,Integer> > listObj = new ArrayList<Entry<String,Integer>>(setObj);
                //Set ---> List

Collections.sort ( listObj, new Comparator<Map.Entry<String,Integer>>(){

public int compare(Map.Entry<String,Integer> o1,Map.Entry<String,Integer> o2){

return (o1.getValue().compareTo(o2.getValue()));
}//compare() method end


}//Comparator end
);

for (Map.Entry<String, Integer> entry : listObj) {
System.out.println(entry.getKey()+""+entry.getValue());
}



}


}

Allowing Map To Accept Duplicate Key's Value !!

Allowing Map To Accept Duplicate Key's Value !!


Q: Map map = new HashMap();
     map.put("sunil", "56");
     map.put("sunil", "78");
     System.out.println(map);

O/p : {sunil=78}

So How we can make map to accept duplicate key's  value? i.e  O/p be Like : {sunil=[56, 78]} ?

Ans:

1. We have to create our own Map implemented class Extending LinkedHashMap.
   
     Take Key type as String.
     Take Value type as List.

Example: public class MapCheckDuplicateKeyAccept extends LinkedHashMap<String, List<String>>


2. Override put() method in the Class.

Example:

package com.test.practice;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class MapCheckDuplicateKeyAccept extends LinkedHashMap<String, List<String>> {

public void put(String key, String number){

List l = get(key);
if(l==null){
l = new ArrayList<>();
super.put(key, l);
}
l.add(number);
}

public static void main(String[] args) {

MapCheckDuplicateKeyAccept map = new MapCheckDuplicateKeyAccept();
map.put("sunil", "56");
map.put("sunil", "78");

System.out.println(map);
}

}

Final Key Word With Collection Types

Final Key Word Collection Types:

Q :  final List list = new LinkedList();
    
    //Will it Work? If it works then 
    
    list.add(23); //Will it work ? If works, then Why?
     
    How to make the List's content Unmodified or Make the list Immutable?

Ans :
   
       final List list = new LinkedList();
       list.add(23);

Both will work. The list will allow to add the values to it.

1. Making a List or any other collection  "fianl"  means :"It's reference cannot be changed."

Example:

  final List list = new LinkedList();
  List anotherListObj = new LinkedList();
  ..........
  list.add(someObject);
  list.add(someOtherObject);

 list = new LinkedList(); //Obviously not work. Error
 list =  anotherListObj;  // Not Work. Error

2. final and immutable Objects:

final  :
             You cannot change the reference to the collection (Object). You can modify the collection / Object the reference points to. You can still add elements to the collection
immutable :
             You cannot modify the contents of the Collection / Object the reference points to. You cannot add elements to the collection.

3.
             A variable can be declared final. A final variable may only be assigned to once. Declaring a variable final can serve as useful documentation that its value will not change and can help avoid programming errors.

It is a compile-time error if a final variable is assigned to unless it is definitely unassigned immediately prior to the assignment.
A blank final is a final variable whose declaration lacks an initializer.

Once a final variable has been assigned, it always contains the same value. If a final variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object.

Therefore, if you wish to enforce that the state reachable through the variable does not change, you have to declare the variable final, use an unmodifiable List (for instance with Collections.unmodifiableList), and make Synapse objects immutable

final List fixedList = Collections.unmodifiableList(someList);


Example:


package com.test.practice;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class FinalKYwordwithCollection {
 public static void main(String[] args) {
  final List<Integer> list = new ArrayList<Integer>();
  
 list.add(12);
 list.add(2);
 list.add(null);
  
        System.out.println(list);
 
        list.add(4);
  
        System.out.println(list);
  
  List<Integer> items = Collections.unmodifiableList(list);

  items.add(40);// java.lang.UnsupportedOperationException

  System.out.println(list);
 
 }

}