Thursday, 21 December 2017

Comparable and Comparator in Java

// Example of Comparable in collection


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

public class ArrayList3 {
public static void main(String as[]) {
ArrayList<Student1> al = new ArrayList<>();
al.add(new Student1(1,"vcd","dvrns"));
al.add(new Student1(10,"avcd","avrns"));
al.add(new Student1(3,"gvcd","cvrns"));
al.add(new Student1(12,"cvcd","vrns"));
System.out.println("Before Sorting");
for(Student1 s: al) {
System.out.println(s.rn+" "+s.name+" "+s.addr);
}
System.out.println("After Sorting");
Collections.sort(al);
for(Student1 s: al) {
System.out.println(s.rn+" "+s.name+" "+s.addr);
}
}
}

class Student1 implements Comparable<Student1> {
int rn;
String name;
String addr;
Student1(int a, String b, String c){
rn = a;
name = b;
addr = c;
}
@Override
public int compareTo(Student1 o) {
if(o.rn > rn)
return 1;
return -1;
}
}



// Example of Comparator in collection


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class ArrayList4 {
@SuppressWarnings("unchecked")
public static void main(String as[]) {
ArrayList<Student4> al = new ArrayList<>();
al.add(new Student4(1,"vcd","dvrns"));
al.add(new Student4(10,"avcd","avrns"));
al.add(new Student4(3,"gvcd","cvrns"));
al.add(new Student4(12,"cvcd","vrns"));
System.out.println("Before Sorting");
for(Student4 s: al) {
System.out.println(s.rn+" "+s.name+" "+s.addr);
}
System.out.println("rn Sorting");
Collections.sort(al, new rnCompare());
for(Student4 s: al) {
System.out.println(s.rn+" "+s.name+" "+s.addr);
}

System.out.println("name Sorting");
Collections.sort(al, new nameCompare());
for(Student4 s: al) {
System.out.println(s.rn+" "+s.name+" "+s.addr);
}
}
}

class Student4 {
int rn;
String name;
String addr;

public Student4(int a, String n, String b) {
rn = a;
name = n;
addr = b;
}

}

class rnCompare implements Comparator {
public int compare(Object o1, Object o2) {
Student4 s1 = (Student4)o1;
Student4 s2 = (Student4)o2;
if(s1.rn > s2.rn)
return 1;
return -1;
}
}

class nameCompare implements Comparator {
public int compare(Object o1, Object o2) {
Student4 s1 = (Student4)o1;
Student4 s2 = (Student4)o2;
return s1.name.compareTo(s2.name);
}
}

1 comment:

  1. for more programming knowledge you can click http://vcdubey98.blogspot.in/p/all-about-programmings.html

    ReplyDelete

Nature Vs Human

  प्रकृति से खिलवाड़ ना कर, वसुधा का अपमान ना कर, हे मानव उठ जाग, देख अपने कर्मों को, कितने दर्द दिये हैं तूने इस वसुधा को, मातृरुप इस धरती ...