Saturday, August 20, 2016
Wednesday, August 10, 2016
Final Finally Finalize
class FinalExample{
public static void main(String[] args){
final int x=100;
x=200;//Compile Time Error
}}
class FinallyExample{
public static void main(String[] args){
try{
int x=300;
}catch(Exception e){System.out.println(e);}
finally{System.out.println("finally block is executed");}
}}
class FinalizeExample{
public void finalize(){System.out.println("finalize called");}
public static void main(String[] args){
FinalizeExample f1=new FinalizeExample();
FinalizeExample f2=new FinalizeExample();
f1=null;
f2=null;
System.gc();
}}
Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final method can't be overridden and final variable value can't be changed.
Finally is used to place important code, it will be executed whether exception is handled or not.
Finalize is used to perform clean up processing just before object is garbage collected.
Final is a keyword.
Finally is a block.
Finalize is a method.
public static void main(String[] args){
final int x=100;
x=200;//Compile Time Error
}}
class FinallyExample{
public static void main(String[] args){
try{
int x=300;
}catch(Exception e){System.out.println(e);}
finally{System.out.println("finally block is executed");}
}}
class FinalizeExample{
public void finalize(){System.out.println("finalize called");}
public static void main(String[] args){
FinalizeExample f1=new FinalizeExample();
FinalizeExample f2=new FinalizeExample();
f1=null;
f2=null;
System.gc();
}}
Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final method can't be overridden and final variable value can't be changed.
Finally is used to place important code, it will be executed whether exception is handled or not.
Finalize is used to perform clean up processing just before object is garbage collected.
Final is a keyword.
Finally is a block.
Finalize is a method.
Sunday, August 7, 2016
How to count number of Instance of a class
public class Bicycle {
...
public static int INSTANCES = 0;
...
//constructor
public Bicycle(int gear, int speed, int seatHeight, String color) {
gear = 0;
speed = 0;
seatHeight = 0;
color ="Unknown";
Bicycle.INSTANCES++;
}
protected void finalize() {
INSTANCES--;
}
}
a. System.gc();
b. Runtime.getRuntime.gc();
...
public static int INSTANCES = 0;
...
//constructor
public Bicycle(int gear, int speed, int seatHeight, String color) {
gear = 0;
speed = 0;
seatHeight = 0;
color ="Unknown";
Bicycle.INSTANCES++;
}
protected void finalize() {
INSTANCES--;
}
}
a. System.gc();
b. Runtime.getRuntime.gc();
Object Equality
Every Java object inherits a set of base methods from java.lang.Object
Creational methods
Object() - Default no-argument constructor
clone() - Returns a new instance of the class
Synchronizing methods
notify() - Sends a signal to a waiting thread (on the current instance)
notifyAll() - Sends a signal to all waiting threads (on the current instance)
wait() - Forces the current thread to wait for a signal (on the current instance)
Equality methods
equals(Object) - Returns true if this instance is equal to the argument
hashCode() - Returns a hash code based on the instance data
Other methods
toString() -Returns a string representation of the object
finalize() - Performs garbage-collection duties
getClass() - Returns the Class object associated with the instance
public class Test{
public static void main(String args[]){
System.out.println(new N()==(new N())); //false
System.out.println(new N().equals(new N())); //false
}
}
class N{}
public class Point {
private static double version = 1.0;
private transient double distance;
private int x, y;
public boolean equals(Object other) {
if (other == this) return true;
if (other == null) return false;
if (getClass() != other.getClass()) return false;
Point point = (Point)other;
return (x == point.x && y == point.y);
}
}
Importantly, if two instances are considered equal by equals(), then they must have the same hash code.
The general contract of hashCode is: Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer,
hashcode does nothing with your business logic, we have to take care it in most cases. Because when your object is put into a hash based container(HashSet, HashMap...), the container puts/gets the element's hashcode.
equals()
equals() is used in most collections to determine if a collection contains a given element. For instance:
List list = new ArrayList();
list.add("123");
boolean contains123 = list.contains("123");
public class Test{
public static void main(String args[]){
List p = new ArrayList();
p.add(new Point());
if(!p.contains(new Point())){
p.add(new Point());
}
System.out.println(p.size());//1
}
}
class Point {
private static double version = 1.0;
private transient double distance;
private int x, y;
public boolean equals(Object other) {
if (other == this) return true;
if (other == null) return false;
if (getClass() != other.getClass()) return false;
Point point = (Point)other;
return (x == point.x && y == point.y);
}
}
public class Employee {
...
public boolean equals(Object o){
if(o == null) return false;
if(!(o instanceof) Employee) return false;
Employee other = (Employee) o;
if(this.employeeId != other.employeeId) return false;
if(! this.firstName.equals(other.firstName)) return false;
if(! this.lastName.equals(other.lastName)) return false;
return true;
}
}
Creational methods
Object() - Default no-argument constructor
clone() - Returns a new instance of the class
Synchronizing methods
notify() - Sends a signal to a waiting thread (on the current instance)
notifyAll() - Sends a signal to all waiting threads (on the current instance)
wait() - Forces the current thread to wait for a signal (on the current instance)
Equality methods
equals(Object) - Returns true if this instance is equal to the argument
hashCode() - Returns a hash code based on the instance data
Other methods
toString() -Returns a string representation of the object
finalize() - Performs garbage-collection duties
getClass() - Returns the Class object associated with the instance
public class Test{
public static void main(String args[]){
System.out.println(new N()==(new N())); //false
System.out.println(new N().equals(new N())); //false
}
}
class N{}
public class Point {
private static double version = 1.0;
private transient double distance;
private int x, y;
public boolean equals(Object other) {
if (other == this) return true;
if (other == null) return false;
if (getClass() != other.getClass()) return false;
Point point = (Point)other;
return (x == point.x && y == point.y);
}
}
Importantly, if two instances are considered equal by equals(), then they must have the same hash code.
The general contract of hashCode is: Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer,
hashcode does nothing with your business logic, we have to take care it in most cases. Because when your object is put into a hash based container(HashSet, HashMap...), the container puts/gets the element's hashcode.
equals()
equals() is used in most collections to determine if a collection contains a given element. For instance:
List list = new ArrayList();
list.add("123");
boolean contains123 = list.contains("123");
public class Test{
public static void main(String args[]){
List
p.add(new Point());
if(!p.contains(new Point())){
p.add(new Point());
}
System.out.println(p.size());//1
}
}
class Point {
private static double version = 1.0;
private transient double distance;
private int x, y;
public boolean equals(Object other) {
if (other == this) return true;
if (other == null) return false;
if (getClass() != other.getClass()) return false;
Point point = (Point)other;
return (x == point.x && y == point.y);
}
}
public class Employee {
...
public boolean equals(Object o){
if(o == null) return false;
if(!(o instanceof) Employee) return false;
Employee other = (Employee) o;
if(this.employeeId != other.employeeId) return false;
if(! this.firstName.equals(other.firstName)) return false;
if(! this.lastName.equals(other.lastName)) return false;
return true;
}
}
Javap java.lang.Objecct
Compiled from "Object.java"
public class java.lang.Object {
public java.lang.Object();
public final native java.lang.Class getClass();
public native int hashCode();
public boolean equals(java.lang.Object);
protected native java.lang.Object clone() throws java.lang.CloneNotSupportedException;
public java.lang.String toString();
public final native void notify();
public final native void notifyAll();
public final native void wait(long) throws java.lang.InterruptedException;
public final void wait(long, int) throws java.lang.InterruptedException;
public final void wait() throws java.lang.InterruptedException;
protected void finalize() throws java.lang.Throwable;
static {};
}
public class java.lang.Object {
public java.lang.Object();
public final native java.lang.Class getClass();
public native int hashCode();
public boolean equals(java.lang.Object);
protected native java.lang.Object clone() throws java.lang.CloneNotSupportedException;
public java.lang.String toString();
public final native void notify();
public final native void notifyAll();
public final native void wait(long) throws java.lang.InterruptedException;
public final void wait(long, int) throws java.lang.InterruptedException;
public final void wait() throws java.lang.InterruptedException;
protected void finalize() throws java.lang.Throwable;
static {};
}
Compiled from "Collection.java"
public interface java.util.Collection extends java.lang.Iterable {
public abstract int size();
public abstract boolean isEmpty();
public abstract boolean contains(java.lang.Object);
public abstract java.util.Iterator iterator();
public abstract java.lang.Object[] toArray();
public abstract T[] toArray(T[]);
public abstract boolean add(E);
public abstract boolean remove(java.lang.Object);
public abstract boolean containsAll(java.util.Collection);
public abstract boolean addAll(java.util.Collection);
public abstract boolean removeAll(java.util.Collection);
public abstract boolean retainAll(java.util.Collection);
public abstract void clear();
public abstract boolean equals(java.lang.Object);
public abstract int hashCode();
}
Compiled from "List.java"
public interface java.util.List extends java.util.Collection {
public abstract int size();
public abstract boolean isEmpty();
public abstract boolean contains(java.lang.Object);
public abstract java.util.Iterator iterator();
public abstract java.lang.Object[] toArray();
public abstract T[] toArray(T[]);
public abstract boolean add(E);
public abstract boolean remove(java.lang.Object);
public abstract boolean containsAll(java.util.Collection);
public abstract boolean addAll(java.util.Collection);
public abstract boolean addAll(int, java.util.Collection);
public abstract boolean removeAll(java.util.Collection);
public abstract boolean retainAll(java.util.Collection);
public abstract void clear();
public abstract boolean equals(java.lang.Object);
public abstract int hashCode();
public abstract E get(int);
public abstract E set(int, E);
public abstract void add(int, E);
public abstract E remove(int);
public abstract int indexOf(java.lang.Object);
public abstract int lastIndexOf(java.lang.Object);
public abstract java.util.ListIterator listIterator();
public abstract java.util.ListIterator listIterator(int);
public abstract java.util.List subList(int, int);
}
Compiled from "Map.java"
public interface java.util.Map {
public abstract int size();
public abstract boolean isEmpty();
public abstract boolean containsKey(java.lang.Object);
public abstract boolean containsValue(java.lang.Object);
public abstract V get(java.lang.Object);
public abstract V put(K, V);
public abstract V remove(java.lang.Object);
public abstract void putAll(java.util.Map);
public abstract void clear();
public abstract java.util.Set keySet();
public abstract java.util.Collection values();
public abstract java.util.Set> entrySet();
public abstract boolean equals(java.lang.Object);
public abstract int hashCode();
}
Compiled from "Set.java"
public interface java.util.Set extends java.util.Collection {
public abstract int size();
public abstract boolean isEmpty();
public abstract boolean contains(java.lang.Object);
public abstract java.util.Iterator iterator();
public abstract java.lang.Object[] toArray();
public abstract T[] toArray(T[]);
public abstract boolean add(E);
public abstract boolean remove(java.lang.Object);
public abstract boolean containsAll(java.util.Collection);
public abstract boolean addAll(java.util.Collection);
public abstract boolean retainAll(java.util.Collection);
public abstract boolean removeAll(java.util.Collection);
public abstract void clear();
public abstract boolean equals(java.lang.Object);
public abstract int hashCode();
}
Compiled from "Collections.java"
public class java.util.Collections {
public static final java.util.Set EMPTY_SET;
public static final java.util.List EMPTY_LIST;
public static final java.util.Map EMPTY_MAP;
public static > void sort(java.util.List);
public static void sort(java.util.List, java.util.Comparator);
public static int binarySearch(java.util.List>, T);
public static int binarySearch(java.util.List, T, java.util.Comparator);
public static void reverse(java.util.List);
public static void shuffle(java.util.List);
public static void shuffle(java.util.List, java.util.Random);
public static void swap(java.util.List, int, int);
public static void fill(java.util.List, T);
public static void copy(java.util.List, java.util.List);
public static > T min(java.util.Collection);
public static T min(java.util.Collection, java.util.Comparator);
public static > T max(java.util.Collection);
public static T max(java.util.Collection, java.util.Comparator);
public static void rotate(java.util.List, int);
public static boolean replaceAll(java.util.List, T, T);
public static int indexOfSubList(java.util.List, java.util.List);
public static int lastIndexOfSubList(java.util.List, java.util.List);
public static java.util.Collection unmodifiableCollection(java.util.Collection);
public static java.util.Set unmodifiableSet(java.util.Set);
public static java.util.SortedSet unmodifiableSortedSet(java.util.SortedSet);
public static java.util.List unmodifiableList(java.util.List);
public static java.util.Map unmodifiableMap(java.util.Map);
public static java.util.SortedMap unmodifiableSortedMap(java.util.SortedMap);
public static java.util.Collection synchronizedCollection(java.util.Collection);
static java.util.Collection synchronizedCollection(java.util.Collection, java.lang.Object);
public static java.util.Set synchronizedSet(java.util.Set);
static java.util.Set synchronizedSet(java.util.Set, java.lang.Object);
public static java.util.SortedSet synchronizedSortedSet(java.util.SortedSet);
public static java.util.List synchronizedList(java.util.List);
static java.util.List synchronizedList(java.util.List, java.lang.Object);
public static java.util.Map synchronizedMap(java.util.Map);
public static java.util.SortedMap synchronizedSortedMap(java.util.SortedMap);
public static java.util.Collection checkedCollection(java.util.Collection, java.lang.Class);
static T[] zeroLengthArray(java.lang.Class);
public static java.util.Set checkedSet(java.util.Set, java.lang.Class);
public static java.util.SortedSet checkedSortedSet(java.util.SortedSet, java.lang.Class);
public static java.util.List checkedList(java.util.List, java.lang.Class);
public static java.util.Map checkedMap(java.util.Map, java.lang.Class, java.lang.Class);
public static java.util.SortedMap checkedSortedMap(java.util.SortedMap, java.lang.Class, java.lang.Class);
public static java.util.Iterator emptyIterator();
public static java.util.ListIterator emptyListIterator();
public static java.util.Enumeration emptyEnumeration();
public static final java.util.Set emptySet();
public static final java.util.List emptyList();
public static final java.util.Map emptyMap();
public static java.util.Set singleton(T);
static java.util.Iterator singletonIterator(E);
public static java.util.List singletonList(T);
public static java.util.Map singletonMap(K, V);
public static java.util.List nCopies(int, T);
public static java.util.Comparator reverseOrder();
public static java.util.Comparator reverseOrder(java.util.Comparator);
public static java.util.Enumeration enumeration(java.util.Collection);
public static java.util.ArrayList list(java.util.Enumeration);
static boolean eq(java.lang.Object, java.lang.Object);
public static int frequency(java.util.Collection, java.lang.Object);
public static boolean disjoint(java.util.Collection, java.util.Collection);
public static boolean addAll(java.util.Collection, T...);
public static java.util.Set newSetFromMap(java.util.Map);
public static java.util.Queue asLifoQueue(java.util.Deque);
static {};
}
Saturday, August 6, 2016
Hashcode and Frequency API
import java.lang.Math;
import java.util.*;
public class HelloWorld
{
public static void main(String[] args)
{
Set set = new HashSet();
Num n = new Num(2);
Num n1 = new Num(2);
/* set.add(n);
set.add(n);
System.out.println(set.size()); //1*/
set.add(n);
set.add(n1);
System.out.println(set.size()); //2
System.out.println(n.hashCode()); //1829164700
System.out.println(n1.hashCode()); //2018699554
System.out.println(Collections.frequency(set,n)); //1
// create array list object
List arrlist = new ArrayList();
// populate the list
arrlist.add("A");
arrlist.add("B");
arrlist.add("C");
arrlist.add("C");
arrlist.add("C");
// check frequensy of 'C'
int freq = Collections.frequency(arrlist, "C");
System.out.println("Frequency of 'C' is: "+freq);
System.out.println(arrlist.size());
for(String x : arrlist){System.out.println(x.hashCode());}
}
}
// this will become its own file too (and these can be in any order)
public class Num
{
private int x;
Num(int x){
this.x=x;
}
}
2
1829164700
2018699554
1
Frequency of 'C' is: 3
5
65
66
67
67
List ll = new ArrayList();
ll.add("one");
ll.add("two");
ll.add("three");
ll.add("four");
ll.add("two");
ll.add("three");
ll.add("two");
ll.add("one");
System.out.println("Actual list: "+ll);
System.out.println("Frequency of 'one': "+Collections.frequency(ll, "one"));
System.out.println("Frequency of 'three': "+Collections.frequency(ll, "three"));
System.out.println("Frequency of 'two': "+Collections.frequency(ll, "two"));
import java.util.*;
public class HelloWorld
{
public static void main(String[] args)
{
Set
Num n = new Num(2);
Num n1 = new Num(2);
/* set.add(n);
set.add(n);
System.out.println(set.size()); //1*/
set.add(n);
set.add(n1);
System.out.println(set.size()); //2
System.out.println(n.hashCode()); //1829164700
System.out.println(n1.hashCode()); //2018699554
System.out.println(Collections.frequency(set,n)); //1
// create array list object
List
// populate the list
arrlist.add("A");
arrlist.add("B");
arrlist.add("C");
arrlist.add("C");
arrlist.add("C");
// check frequensy of 'C'
int freq = Collections.frequency(arrlist, "C");
System.out.println("Frequency of 'C' is: "+freq);
System.out.println(arrlist.size());
for(String x : arrlist){System.out.println(x.hashCode());}
}
}
// this will become its own file too (and these can be in any order)
public class Num
{
private int x;
Num(int x){
this.x=x;
}
}
2
1829164700
2018699554
1
Frequency of 'C' is: 3
5
65
66
67
67
List
ll.add("one");
ll.add("two");
ll.add("three");
ll.add("four");
ll.add("two");
ll.add("three");
ll.add("two");
ll.add("one");
System.out.println("Actual list: "+ll);
System.out.println("Frequency of 'one': "+Collections.frequency(ll, "one"));
System.out.println("Frequency of 'three': "+Collections.frequency(ll, "three"));
System.out.println("Frequency of 'two': "+Collections.frequency(ll, "two"));
Java Best Tutorial
http://www.java2novice.com/
Set uniqueSet = new HashSet(list);
System.out.println("\nSorted Map");
Map treeMap = new TreeMap(map);
public static void printMap(Map map){
for (Map.Entry entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : "
+ entry.getValue());
}
}
Set
System.out.println("\nSorted Map");
Map
public static void printMap(Map
for (Map.Entry
System.out.println("Key : " + entry.getKey() + " Value : "
+ entry.getValue());
}
}
Collection API
Collection -Interface
List,Map,Map.Entry,Compartor,Comparable -Interface
Collections,Arrays- class
List,Map,Map.Entry,Compartor,Comparable -Interface
Collections,Arrays- class
Call By Referance in JAVA
public static void main ( String[] args ) {
Number a = new Number();
a.x=3;
System.out.println("Value of a.x before calling increment() is "+a.x);
increment(a);
System.out.println("Value of a.x after calling increment() is "+a.x);
}
public static void increment(Number n) {
System.out.println("Value of n.x before incrementing x is "+n.x);
n.x=n.x+1;
System.out.println("Value of n.x after incrementing x is "+n.x);
}
Value of a.x before calling increment() is 3
Value of n.x before incrementing x is 3
Value of n.x after incrementing x is 4
Value of a.x after calling increment() is 4
Number a = new Number();
a.x=3;
System.out.println("Value of a.x before calling increment() is "+a.x);
increment(a);
System.out.println("Value of a.x after calling increment() is "+a.x);
}
public static void increment(Number n) {
System.out.println("Value of n.x before incrementing x is "+n.x);
n.x=n.x+1;
System.out.println("Value of n.x after incrementing x is "+n.x);
}
Value of a.x before calling increment() is 3
Value of n.x before incrementing x is 3
Value of n.x after incrementing x is 4
Value of a.x after calling increment() is 4
Sort a list by multiple attibute - chained comparator
sorting a list of employees by their job title, then by age, and then by salary
chained comparator - CompareToBuilder class of the Apache Commons Lang library.
public class Employee {
private String name;
private String jobTitle;
private int age;
private int salary;
public Employee(String name, String jobTitle, int age, int salary) {
this.name = name;
this.jobTitle = jobTitle;
this.age = age;
this.salary = salary;
}
// getters and setters
public String toString() {
return String.format("%s\t%s\t%d\t%d", name, jobTitle, age, salary);
}
}
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
/**
* This is a chained comparator that is used to sort a list by multiple
* attributes by chaining a sequence of comparators of individual fields
* together.
*
*/
public class EmployeeChainedComparator implements Comparator {
private List> listComparators;
@SafeVarargs
public EmployeeChainedComparator(Comparator... comparators) {
this.listComparators = Arrays.asList(comparators);
}
@Override
public int compare(Employee emp1, Employee emp2) {
for (Comparator comparator : listComparators) {
int result = comparator.compare(emp1, emp2);
if (result != 0) {
return result;
}
}
return 0;
}
}
import java.util.Comparator;
/**
* This comparator compares two employees by their job titles.
*
*/
public class EmployeeJobTitleComparator implements Comparator {
@Override
public int compare(Employee emp1, Employee emp2) {
return emp1.getJobTitle().compareTo(emp2.getJobTitle());
}
}
import java.util.Comparator;
/**
* This comparator compares two employees by their ages.
*
*/
public class EmployeeAgeComparator implements Comparator {
@Override
public int compare(Employee emp1, Employee emp2) {
return emp1.getAge() - emp2.getAge();
}
}
import java.util.Comparator;
/**
* This comparator compares two employees by their salaries.
*
*/
public class EmployeeSalaryComparator implements Comparator {
@Override
public int compare(Employee emp1, Employee emp2) {
return emp1.getSalary() - emp2.getSalary();
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* This program demonstrates how to sort a list collection by multiple
* attributes using a chained comparator.
*
*
*/
public class SortingMultipleAttributesExample {
public static void main(String[] args) {
System.out.println("===== SORTING BY MULTIPLE ATTRIBUTES =====");
List listEmployees = new ArrayList();
listEmployees.add(new Employee("Tom", "Developer", 45, 80000));
listEmployees.add(new Employee("Sam", "Designer", 30, 75000));
listEmployees.add(new Employee("Bob", "Designer", 45, 134000));
listEmployees.add(new Employee("Peter", "Programmer", 25, 60000));
listEmployees.add(new Employee("Tim", "Designer", 45, 130000));
listEmployees.add(new Employee("Craig", "Programmer", 30, 52000));
listEmployees.add(new Employee("Anne", "Programmer", 25, 51000));
listEmployees.add(new Employee("Alex", "Designer", 30, 120000));
listEmployees.add(new Employee("Bill", "Programmer", 22, 30000));
listEmployees.add(new Employee("Samuel", "Developer", 28, 80000));
listEmployees.add(new Employee("John", "Developer", 35, 67000));
listEmployees.add(new Employee("Patrick", "Developer", 35, 140000));
listEmployees.add(new Employee("Alice", "Programmer", 35, 80000));
listEmployees.add(new Employee("David", "Developer", 35, 99000));
listEmployees.add(new Employee("Jane", "Designer", 30, 82000));
System.out.println("*** Before sorting:");
for (Employee emp : listEmployees) {
System.out.println(emp);
}
Collections.sort(listEmployees, new EmployeeChainedComparator(
new EmployeeJobTitleComparator(),
new EmployeeAgeComparator(),
new EmployeeSalaryComparator())
);
System.out.println("\n*** After sorting:");
for (Employee emp : listEmployees) {
System.out.println(emp);
}
}
}
===== SORTING BY MULTIPLE ATTRIBUTES =====
*** Before sorting:
Tom Developer 45 80000
Sam Designer 30 75000
Bob Designer 45 134000
Peter Programmer 25 60000
Tim Designer 45 130000
Craig Programmer 30 52000
Anne Programmer 25 51000
Alex Designer 30 120000
Bill Programmer 22 30000
Samuel Developer 28 80000
John Developer 35 67000
Patrick Developer 35 140000
Alice Programmer 35 80000
David Developer 35 99000
Jane Designer 30 82000
*** After sorting:
Sam Designer 30 75000
Jane Designer 30 82000
Alex Designer 30 120000
Tim Designer 45 130000
Bob Designer 45 134000
Samuel Developer 28 80000
John Developer 35 67000
David Developer 35 99000
Patrick Developer 35 140000
Tom Developer 45 80000
Bill Programmer 22 30000
Anne Programmer 25 51000
Peter Programmer 25 60000
Craig Programmer 30 52000
Alice Programmer 35 80000
import java.util.Comparator;
import org.apache.commons.lang3.builder.CompareToBuilder;
/**
* This comparator sorts a list of Employees by job title, age and salary
* into ascending order.
*
*/
public class EmployeeComparator implements Comparator {
@Override
public int compare(Employee o1, Employee o2) {
return new CompareToBuilder()
.append(o1.getJobTitle(), o2.getJobTitle())
.append(o1.getAge(), o2.getAge())
.append(o1.getSalary(), o2.getSalary()).toComparison();
}
}
Collections.sort(listEmployees, new EmployeeComparator())
chained comparator - CompareToBuilder class of the Apache Commons Lang library.
public class Employee {
private String name;
private String jobTitle;
private int age;
private int salary;
public Employee(String name, String jobTitle, int age, int salary) {
this.name = name;
this.jobTitle = jobTitle;
this.age = age;
this.salary = salary;
}
// getters and setters
public String toString() {
return String.format("%s\t%s\t%d\t%d", name, jobTitle, age, salary);
}
}
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
/**
* This is a chained comparator that is used to sort a list by multiple
* attributes by chaining a sequence of comparators of individual fields
* together.
*
*/
public class EmployeeChainedComparator implements Comparator
private List
@SafeVarargs
public EmployeeChainedComparator(Comparator
this.listComparators = Arrays.asList(comparators);
}
@Override
public int compare(Employee emp1, Employee emp2) {
for (Comparator
int result = comparator.compare(emp1, emp2);
if (result != 0) {
return result;
}
}
return 0;
}
}
import java.util.Comparator;
/**
* This comparator compares two employees by their job titles.
*
*/
public class EmployeeJobTitleComparator implements Comparator
@Override
public int compare(Employee emp1, Employee emp2) {
return emp1.getJobTitle().compareTo(emp2.getJobTitle());
}
}
import java.util.Comparator;
/**
* This comparator compares two employees by their ages.
*
*/
public class EmployeeAgeComparator implements Comparator
@Override
public int compare(Employee emp1, Employee emp2) {
return emp1.getAge() - emp2.getAge();
}
}
import java.util.Comparator;
/**
* This comparator compares two employees by their salaries.
*
*/
public class EmployeeSalaryComparator implements Comparator
@Override
public int compare(Employee emp1, Employee emp2) {
return emp1.getSalary() - emp2.getSalary();
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* This program demonstrates how to sort a list collection by multiple
* attributes using a chained comparator.
*
*
*/
public class SortingMultipleAttributesExample {
public static void main(String[] args) {
System.out.println("===== SORTING BY MULTIPLE ATTRIBUTES =====");
List
listEmployees.add(new Employee("Tom", "Developer", 45, 80000));
listEmployees.add(new Employee("Sam", "Designer", 30, 75000));
listEmployees.add(new Employee("Bob", "Designer", 45, 134000));
listEmployees.add(new Employee("Peter", "Programmer", 25, 60000));
listEmployees.add(new Employee("Tim", "Designer", 45, 130000));
listEmployees.add(new Employee("Craig", "Programmer", 30, 52000));
listEmployees.add(new Employee("Anne", "Programmer", 25, 51000));
listEmployees.add(new Employee("Alex", "Designer", 30, 120000));
listEmployees.add(new Employee("Bill", "Programmer", 22, 30000));
listEmployees.add(new Employee("Samuel", "Developer", 28, 80000));
listEmployees.add(new Employee("John", "Developer", 35, 67000));
listEmployees.add(new Employee("Patrick", "Developer", 35, 140000));
listEmployees.add(new Employee("Alice", "Programmer", 35, 80000));
listEmployees.add(new Employee("David", "Developer", 35, 99000));
listEmployees.add(new Employee("Jane", "Designer", 30, 82000));
System.out.println("*** Before sorting:");
for (Employee emp : listEmployees) {
System.out.println(emp);
}
Collections.sort(listEmployees, new EmployeeChainedComparator(
new EmployeeJobTitleComparator(),
new EmployeeAgeComparator(),
new EmployeeSalaryComparator())
);
System.out.println("\n*** After sorting:");
for (Employee emp : listEmployees) {
System.out.println(emp);
}
}
}
===== SORTING BY MULTIPLE ATTRIBUTES =====
*** Before sorting:
Tom Developer 45 80000
Sam Designer 30 75000
Bob Designer 45 134000
Peter Programmer 25 60000
Tim Designer 45 130000
Craig Programmer 30 52000
Anne Programmer 25 51000
Alex Designer 30 120000
Bill Programmer 22 30000
Samuel Developer 28 80000
John Developer 35 67000
Patrick Developer 35 140000
Alice Programmer 35 80000
David Developer 35 99000
Jane Designer 30 82000
*** After sorting:
Sam Designer 30 75000
Jane Designer 30 82000
Alex Designer 30 120000
Tim Designer 45 130000
Bob Designer 45 134000
Samuel Developer 28 80000
John Developer 35 67000
David Developer 35 99000
Patrick Developer 35 140000
Tom Developer 45 80000
Bill Programmer 22 30000
Anne Programmer 25 51000
Peter Programmer 25 60000
Craig Programmer 30 52000
Alice Programmer 35 80000
import java.util.Comparator;
import org.apache.commons.lang3.builder.CompareToBuilder;
/**
* This comparator sorts a list of Employees by job title, age and salary
* into ascending order.
*
*/
public class EmployeeComparator implements Comparator
@Override
public int compare(Employee o1, Employee o2) {
return new CompareToBuilder()
.append(o1.getJobTitle(), o2.getJobTitle())
.append(o1.getAge(), o2.getAge())
.append(o1.getSalary(), o2.getSalary()).toComparison();
}
}
Collections.sort(listEmployees, new EmployeeComparator())
Friday, August 5, 2016
Subscribe to:
Posts (Atom)
உப்பு மாங்காய்
சுருக்குப்பை கிழவி. சுருக்கங்கள் சூழ் கிழவி. பார்க்கும் போதெல்லாம் கூடையுடனே குடியிருப்பாள். கூடை நிறைய குட்டி குட்டி மாங்காய்கள். வெட்டிக்க...
-
கந்தன் வேலைக்குச் சென்று கிட்டத்தட்ட பத்து ஆண்டுகளுக்கு பிறகு சொந்த ஊர் திரும்பி இருந்தான். காளிக் கோயிலைத் தாண்டி தான் அவன் வீட்ட...
-
பிரேமாவின் மூத்த ஆண் குழந்தைக்கு முன் பிறந்த இளைய பெண் குழந்தை அவள். வயலும் சேறும் இரண்டற கலந்த ஊர். முழுதாய் மூன்றாம் வகுப்பைத் ...