Drop Down

Showing posts with label Collections. Show all posts
Showing posts with label Collections. Show all posts

Tuesday, March 5, 2019

SortMapByValue_TreeMap

package comparator.Emp;

import java.util.*;

public class SortMapByValue_TreeMap
{
public static void main(String[] args)
{
Map <String,String> unsortedmap = new HashMap<>();
unsortedmap.put("one", "one");
unsortedmap.put("tree", "tree");
unsortedmap.put("mount", "mount");
unsortedmap.put("bird", "bird");
unsortedmap.put("house", "house");
System.out.println("***************Unsorted Map**************");
printmap(unsortedmap);
System.out.println("************After sorting Map*************");
        Map<String, String> sortedMap = sortMap(unsortedmap);
        printmap(sortedMap);


}

private static Map<String, String> sortMap(Map<String, String> unsortedmap)
{
// copy unsortedmap to TreeMap
TreeMap <String,String> tm = new TreeMap<>(new SortMapComparator());
for(Map.Entry<String,String> entry : unsortedmap.entrySet())
{
tm.put(entry.getKey(), entry.getValue());
}
return tm;
}

private static void printmap(Map<String, String> unsortedmap)
{
  for(Map.Entry<String,String> entry  : unsortedmap.entrySet())
  {
  System.out.println(entry.getKey()+" : "+entry.getValue());
  }

}

}
=============================================================
package comparator.Emp;

import java.util.Comparator;

public class SortMapComparator implements Comparator <String>
{

@Override
public int compare(String s1 , String s2)
{
    return s1.compareTo(s2);
}


}
==============================================================

Concurrent Modification Exception

package concurrent_Collection;
/*One Thread iterating Collection Object and other thread trying to modify it...
 This leads to Concurrent Modification Exception
java.util.ConcurrentModificationException*/

import java.util.*;

public class ConcurrentModificationException extends Thread
{
static ArrayList list = new ArrayList();
public void run()
{
try
{
  Thread.sleep(700);
}
catch(Exception e)
{
System.out.println(e.toString());
}
System.out.println("Child Thread adding ---> 10");
list.add(10);
}

public static void main(String[] args) throws Exception
{
  list.add(59);
  list.add(788);
  list.add(45);
  list.add(88);
  ConcurrentModificationException thread = new ConcurrentModificationException();
  thread.start();
  Iterator itr = list.iterator();
  while(itr.hasNext())
  {
  System.out.println(itr.next());
  Thread.sleep(500);
  }

}

}

Sort HashMap according to Value

package test;

import java.util.*;

//map ---list--sort--map(display)
public class SortMap_Value
{
public static void main(String[] args)
{
Map<String,Integer> map = new HashMap<>();
map.put("A", 78);
map.put("B", 55);
map.put("C", 807);
map.put("D", 34);
map.put("E", 89);
map.put("F", 700);

//List<Map.Entry<String, Integer>> list = new LinkedList<>(map.entrySet());
List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, new MyComparator2());

Map<String,Integer> map2 = new LinkedHashMap<>();
for(Map.Entry<String,Integer> entry : list)
{
map2.put(entry.getKey(), entry.getValue());
}
for(Map.Entry<String,Integer> entry : map2.entrySet())
{
System.out.println(entry.getKey()+" : "+entry.getValue());
}


}

}
========================================
package test;

import java.util.Comparator;import java.util.Map;
import java.util.Map.Entry;


public class MyComparator2 implements Comparator<Map.Entry<String,Integer>>
{

@Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2)
{

//return o1.getValue().compareTo(o2.getValue());
return o2.getValue().compareTo(o1.getValue());
}

}
=========================================


Thursday, February 7, 2019

Sort Map According to its Value (Used Comparator ,List & LinkedHashMap)


  • package sort_Map_byValue;
  • import java.util.*;

  • //Program to sort Map value
  • //Map--->copy entry to List--->sort List using comparator-->copy to new Map-->display
  • public class SortMapbyValue
  • {
  • public static void main(String[] args)
  • {
  • //Map create
  • Map <String,Integer> map = new HashMap<>();
  • map.put("A", 65);
  • map.put("B", 60);
  • map.put("C", 75);
  • map.put("D", 97);
  • map.put("E", 90);
  • map.put("F", 85);
  • map.put("G", 81);
  • map.put("H", 75);
  • //copy to List
  • //create linked List & pass entryset--> as it maintains the insertion order)
  • List<Map.Entry<String,Integer>> list = new LinkedList<>(map.entrySet());
  • //Sort List
  • //MyComparator mc = new MyComparator();
  • Collections.sort(list, new MyComparator());

  • //copy the sorted to new LinkedHashMap (temp)
  • Map<String,Integer> sortedMap = new LinkedHashMap<>();

  • for(Map.Entry<String, Integer> entry : list)
  • {
  • sortedMap.put(entry.getKey(), entry.getValue());
  • }
  • //Dispaly the Sorted Map (Soerted According to Value)

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

  • }

  • }
  • =================================================
  • package sort_Map_byValue;

  • import java.util.Comparator;
  • import java.util.Map;

  • public class MyComparator implements Comparator<Map.Entry<String, Integer>>
  • {

  • @Override
  • public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2)
  • {
  • return (o1.getValue()).compareTo(o2.getValue());
  • }

  • }
  • ==================================================

Sort Map by Values

package test;
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 SortMapbyValues
{
    public static boolean ASC = true;
    public static boolean DESC = false;

    public static void main(String[] args)
    {     
        Map<String, Integer> unsortMap = new HashMap<>();
        unsortMap.put("B", 55);
        unsortMap.put("A", 80);
        unsortMap.put("D", 20);
        unsortMap.put("C", 70);

        System.out.println("Before sorting......");
        printMap(unsortMap);

        System.out.println("After sorting ascending order......");
        Map<String, Integer> sortedMapAsc = sortByComparator(unsortMap, ASC);
        printMap(sortedMapAsc);


        System.out.println("After sorting descindeng order......");
        Map<String, Integer> sortedMapDesc = sortByComparator(unsortMap, DESC);
        printMap(sortedMapDesc);

    }

    private static Map<String, Integer> sortByComparator(Map<String, Integer> unsortMap, final boolean order)
    {

        List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(unsortMap.entrySet());

        // Sorting the list based on values
        Collections.sort(list, new Comparator<Entry<String, Integer>>()
        {
            public int compare(Entry<String, Integer> o1,
                    Entry<String, Integer> o2)
            {
                if (order)
                {
                    return o1.getValue().compareTo(o2.getValue());
                }
                else
                {
                    return o2.getValue().compareTo(o1.getValue());

                }
            }
        });

        // Maintaining insertion order with the help of LinkedList
        Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
        for (Entry<String, Integer> entry : list)
        {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        return sortedMap;
    }

    public static void printMap(Map<String, Integer> map)
    {
        for (Entry<String, Integer> entry : map.entrySet())
        {
            System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
        }
    }
}

Sort Map using comparator

package test;

import java.util.*;

public class SortMap_TreeMap
{
public static void main(String[] args)
{
Map <String,String> unsortedmap = new HashMap<>();
unsortedmap.put("one", "one");
unsortedmap.put("tree", "tree");
unsortedmap.put("mount", "mount");
unsortedmap.put("bird", "bird");
unsortedmap.put("house", "house");
System.out.println("***************Unsorted Map**************");
printmap(unsortedmap);
System.out.println("************After sorting Map*************");
        Map<String, String> sortedMap = sortMap(unsortedmap);
        printmap(sortedMap);


}

private static Map<String, String> sortMap(Map<String, String> unsortedmap)
{
// copy unsortedmap to TreeMap
TreeMap <String,String> tm = new TreeMap<>(new SortMapComparator());
for(Map.Entry<String,String> entry : unsortedmap.entrySet())
{
tm.put(entry.getKey(), entry.getValue());
}
return tm;
}

private static void printmap(Map<String, String> unsortedmap)
{
  for(Map.Entry<String,String> entry  : unsortedmap.entrySet())
  {
  System.out.println(entry.getKey()+" : "+entry.getValue());
  }

}

}
=========================================
package test;

import java.util.Comparator;

public class SortMapComparator implements Comparator <String>
{

@Override
public int compare(String s1 , String s2) 
{
    return s1.compareTo(s2);
}

}

Wednesday, February 6, 2019

Sort Map by Key

package interview;
import java.util.*;
//Sort HashMap according to key
//Map -->Map(to keeep sorted items)---->TreeMap---(default comparable)-->Sorted
public class SortHashMap_1 {

public static void main(String[] args)
{
  Map <String, String> map = new HashMap<>();
  map.put("orange", "orange");
  map.put("guava", "guava");
  map.put("mango", "mango");
  map.put("pineapple", "pineapple");
  map.put("banana", "banana");
  map.put("grapes", "grapes");
  System.out.println(map);
  //TreeMap is a class which follows some sorting order for elements
  Map <String,String> map2 = new TreeMap(map);
  //Now display
  System.out.println("*********************Sorted *************************");
  for(Map.Entry<String,String> entry : map2.entrySet())
  {

  System.out.println(entry.getKey() +" : "+entry.getValue());
  }



}

}

Sort Map using Key

package test;

import java.util.Map;
import java.util.TreeMap;

public class Sorting_TreeMap_DNSO {

public static void main(String[] args)
{
  Map <String,String>  map = new TreeMap<>();  //Sorting : Default Natural(Keys)
  map.put("orange", "orange");
  map.put("guava", "guava");
  map.put("mango", "mango");
  map.put("pineapple", "pineapple");
  map.put("banana", "banana");
  System.out.println(map);

}

}

Thursday, January 17, 2019

Ways to Iterate HashMap

package collection_Codes;

import java.util.HashMap;

public class Hashmap_Iterate2 {

public static void main(String[] args)
{
HashMap<String,String> m = new HashMap<String,String>();
m.put("name", "Amit");
m.put("college","NIT");
m.put("profession","SE");

for(String s : m.keySet())
{
String val = m.get(s);
System.out.println(s +" "+val);
}

}

}
========================================================================

package collection_Codes;
//Interface Entry is present inside MAP Interface. Entry has 3 methods:
// 1) Object getKey();
// 2) Object getValue();
// 3) Object setValue(Object );
//**********************************
import java.util.HashMap;
import java.util.Map;

public class HashMap_Iterate1 {

public static void main(String[] args) 
{
HashMap<String,String> m = new HashMap<String,String>();
m.put("name", "Amit");
m.put("college","NIT");
m.put("profession","SE");
for(Map.Entry<String,String> entry : m.entrySet())
{
System.out.println(entry.getKey()+" = "+entry.getValue());
}

}

}
===================================================================
package ERRORS;

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

public class Test {

public static void main(String[] args)
{
   Map<String,String> m  = new HashMap<>();
   m.put("game", "FOOTBALL");
   m.put("food", "Haldiram Full Thali");
   m.put("hobby", "WINNING");
   m.put("place", "America");
   m.put("bd", "7 AUGUST");
   // Now Iterate
 
   //********************************* Method 1
   for(String s1 : m.keySet())
   {
  System.out.println(s1 +" "+m.get(s1));
   }
 
   //********************************* Method 2
 
   Set <Entry<String , String>> entry = m.entrySet();  
   for(Entry<String, String> s1 : entry)
   {
   System.out.println(s1.getKey()+"  ~  "+s1.getValue());
   }  

}

}
========================================================================

COMPARATOR::: Sort Employee Object using employee id

package comparator.Emp;
//When we are not allowed to change Class Employee code (i.e we can't implement Comparable)
//We use comparator Interface.
public class Employee
{
int empid;
String name;
int deptid;
public Employee(int empid, String name, int deptid)
{
super();
this.empid = empid;
this.name = name;
this.deptid = deptid;
}
/*@Override
public String toString() {
return "Empid=" + empid + ", Name=" + name + ", Deptid=" + deptid;
}*/


}
==========================================
package comparator.Emp;
import java.util.*;
//Sort the Employeee Class using empid -- Use Comparator
public class Emp_Runner {

public static void main(String[] args) 
{
Employee emp1  = new Employee(111,"Amit",549);
Employee emp2  = new Employee(674,"Dinesh",549);
Employee emp3  = new Employee(352,"Manohar",667);
Employee emp4  = new Employee(642,"Dilip",889);
Employee emp5  = new Employee(133,"Govind",667);
 
List list = new ArrayList();
list.add(emp1);
list.add(emp2);
list.add(emp3);
list.add(emp4);
list.add(emp5);
 
Comparator comp = new Emp_Comp(); //Comparator is Interface so we can't instanciate it.
Collections.sort(list,new Emp_Comp());  //call to compare() .... from here
 
Iterator itr = list.iterator();
while(itr.hasNext())
{
Employee emp = (Employee) itr.next();
System.out.println("Empid=" + emp.empid + ", Name=" + emp.name + ", Deptid=" + emp.deptid);
 
}
 
 
}


}
==========================================
package comparator.Emp;

import java.util.Comparator;

public class Emp_Comp implements Comparator<Employee>
{

@Override
public int compare(Employee e1, Employee e2) 
{
if(e1.empid > e2.empid)
{
return 1;
}
else return 
-1;
}

}
============================================
============================================

COMPARATOR:: Sort simple ArrayList of STRING & INTEGER

package ERRORS;
// Use of Comparator
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class Test
{

public static void main(String[] args)
{
//*********List of Integers*************
  ArrayList list = new ArrayList();
  list.add(98);
  list.add(89);
  list.add(108);
  list.add(897);
  list.add(55);

  Comparator<Integer> comp_int = new Test2_Comp();
  Collections.sort(list,new Test2_Comp());
  System.out.println(list);
  System.out.println("********************************");

//*********List of Strings*************
  ArrayList list2 = new ArrayList();
  list2.add("Tiger");
  list2.add("Elephant");
  list2.add("Aeroplane");
  list2.add("ink");
  list2.add("apricote");

  //To Sort list >> equalsEgnoreCase().....Aa Bb Cc...
  Comparator<String> comp = new Test_Comp();
  Collections.sort(list2,new Test_Comp());
  System.out.println(list2);
}

}

=========================================

package ERRORS;

import java.util.Comparator;
import java.util.List;

public class Test_Comp implements  Comparator<String>
{

@Override
public int compare(String s1, String s2)
{
//System.out.println(s2);
return s1.compareToIgnoreCase(s2);
//return 0;
}

}
==========================================
package ERRORS;

import java.util.Comparator;

public class Test2_Comp implements Comparator <Integer>
{
public int compare(Integer integer1, Integer integer2)
{
if(integer1 > integer2)
return 1;
else
return -1;
}

}
===========================================
===========================================
NOTE:
--------
To sort integers according to last digit use the below code.
----------------------------------------------------------------------
public int compare(Integer integer1, Integer integer2)
{
if(integer1%10 > integer2%10)
return 1;
else
return -1;
}
----------------------------------------------------------------------




Comparable:::::Sorting Book Object according to Book ID

package Coparable_Std;
//Sorting Book Object according to Book ID
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

public class Book_main {

public static void main(String[] args)
{
  Book_comp book1 = new Book_comp(183,"Book1",456);
  Book_comp book2 = new Book_comp(675,"Book2",799);
  Book_comp book3 = new Book_comp(335,"Book3",5454);
  Book_comp book4 = new Book_comp(832,"Book4",454);
  Book_comp book5 = new Book_comp(331,"Book5",778);
  Book_comp book6 = new Book_comp(113,"Book6",234);
  Book_comp book7 = new Book_comp(674,"Book7",788);

  ArrayList list = new ArrayList();
  list.add(book1);
  list.add(book2);
  list.add(book3);
  list.add(book4);
  list.add(book5);
  list.add(book6);
  list.add(book7);

  Collections.sort(list);
  //System.out.println(list); // works when we overrides toString() in Book_comp & no need for below codes for iterate
  Iterator itr = list.iterator();
  while(itr.hasNext())
  {
  Book_comp book = (Book_comp) itr.next();
      System.out.println("Book ID: "+book.book_Id+" ~ Book Name: "+book.book_Name+" ~ Book Price: "+book.book_Price);
   }

}

}
------------------------
-----------------------
package Coparable_Std;

public class Book_comp implements Comparable<Book_comp>
{
int book_Id;
String book_Name;
double book_Price;
public Book_comp(int book_Id, String book_Name, double book_Price) 
{
super();
this.book_Id = book_Id;
this.book_Name = book_Name;
this.book_Price = book_Price;
}
public int getBook_Id() {
return book_Id;
}
public void setBook_Id(int book_Id) {
this.book_Id = book_Id;
}
public String getBook_Name() {
return book_Name;
}
public void setBook_Name(String book_Name) {
this.book_Name = book_Name;
}
public double getBook_Price() {
return book_Price;
}
public void setBook_Price(double book_Price) {
this.book_Price = book_Price;
}
/*@Override
public String toString() {
return "Book_comp [book_Id=" + book_Id + ", book_Name=" + book_Name + ", book_Price=" + book_Price + "]";
}*/

@Override
public int compareTo(Book_comp o) 
{
  if(this.book_Id > o.book_Id)
return 1;
  else
  return -1;
}

}
========================================================================

Wednesday, January 16, 2019

Comparable:::::Sort an object using comparable

package Coparable_Std;
//Sort an object using comparable

import java.util.ArrayList;
import java.util.*;

public class Runner_Student_Comparable
{

public static void main(String[] args)
{

Student_Comparable sc1 = new Student_Comparable(12,"maths","Michle");
Student_Comparable sc2 = new Student_Comparable(100,"Science","Hitler");
Student_Comparable sc3 = new Student_Comparable(67,"hindi","Dicosta");
Student_Comparable sc4 = new Student_Comparable(99,"Urdu","Hillary");
Student_Comparable sc5 = new Student_Comparable(10,"Marathi","Donald");

ArrayList al = new ArrayList();
al.add(sc1);
al.add(sc2);
al.add(sc3);
al.add(sc4);
al.add(sc5);
Collections.sort(al); // Yaha se internally compareTo() call hota hai..[Comparable (I)]

Iterator itr = al.iterator();
while(itr.hasNext())
{
Student_Comparable sc = (Student_Comparable)itr.next();
System.out.println(sc.name +" ~ " +sc.roll+" ~ "+sc.subject);
}


}

}
-----------------------
-----------------------
package Coparable_Std;

import java.util.ArrayList;

public class Student_Comparable implements Comparable<Student_Comparable>
{
int roll;
String subject;
String name;
Student_Comparable(int a, String b, String c)
{
this.roll = a;
this.subject = b;
this.name = c;
}

public int compareTo(Student_Comparable sc) 
{
//System.out.println("Inside compareTo()");
if(roll == sc.roll)
{
return 0;
}
if(roll > sc.roll)
{
return -1;
}
else
return 1;
}

}

Comparable :::::Sort Employee OBJECT according to Names

package Coparable_Std;
//Sort Employee OBJECT according to Names.......
public class Employee implements Comparable<Employee>
{
int e_id;
int dept_id;
String name;

Employee(int eid,int dept,String name)
{
this.e_id = eid;
this.dept_id = dept;
this.name = name;
}

@Override
public int compareTo(Employee emp)
{
return this.name.compareTo(emp.name); //** For Strings we don't need to do anything
}   //coz String has it own implemented compareTo() for sorting

}
--------
--------
package Coparable_Std;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

public class Employee_Runner {

public static void main(String[] args) 
{
  
  Employee e1 = new Employee(104,072,"Giridhar");
  Employee e2 = new Employee(145,911,"Amit");
  Employee e3 = new Employee(167,053,"Mallik");
  Employee e4 = new Employee(134,884,"Pranav");
  Employee e5 = new Employee(101,445,"Ginny");
  ArrayList list = new ArrayList();
  list.add(e1);
  list.add(e2);
  list.add(e3);
  list.add(e4);
  list.add(e5);   
  Collections.sort(list);
  Iterator itr = list.iterator();
  while(itr.hasNext())
  {
  Employee emp = (Employee)itr.next();
  System.out.println(emp.e_id+"  "+emp.dept_id+"   "+emp.name);
  }  

}

}

Java 8 Notes Pics