Using comparable and comparator in java collection


   Comparable

   Comparator

1 this interface allows the object to compare itself with another object while sorting the list of such type objects. This interface provide the provision to compare two different objects.
2 The objects those implements Comparable interface are sorted automatically without specifying any other comparator. Comparator is passed as arguments to the method who need to sort some objects.
3 less flexible more flexible
4 uses compareTo(object2) method it has compare(object1,object2) method
5 this interface is not a part of collection API. It belongs to java.lang Packages this interface belongs to java.util package.

Using Comparable
package collection.examples;

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

class Contact implements Comparable<Contact>{
    String name;
    String email;
    int phone;
    public Contact(String name, String email, int phone) {
        this.name = name;
        this.email = email;
        this.phone = phone;
    }
    public int compareTo(Contact otherContact) {
        return this.name.compareTo(otherContact.name);
    }

    @Override
    public String toString() {
        return "Contact{" + "name=" + name + ", email=" + email + ", phone=" + phone + '}';
    }
}

 public class UsingComparable {
    public static void main(String[] args) {
        Contact c1=new Contact("rbc","mail1@gmail.com",2424342);
        Contact c2=new Contact("tbc","mail2@gmail.com",2424342);
        Contact c3=new Contact("bcc","mail3@gmail.com",2424342);
        ArrayList<Contact> al=new ArrayList<Contact>();
        al.add(c1);
        al.add(c2);
        al.add(c3);
        Collections.sort(al);
        for (Contact contact : al) {
            System.out.println(contact);
        }
    }
}

Using Comparator 
 package collection.examples;

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

class Contact1 {
    String name;
    String email;
    int phone;
    public Contact1(String name, String email, int phone) {
        this.name = name;
        this.email = email;
        this.phone = phone;
    }
 
    @Override
    public String toString() {
        return "Contact1{" + "name=" + name + ", email=" + email + ", phone=" + phone + '}';
    }
    
}
class MyComparator implements Comparator<Contact1>{

    public int compare(Contact1 o1, Contact1 o2) {
        //comparing name from both objects
        return o1.name.compareTo(o2.name);
    }   
}
public class UsingComparator {
    public static void main(String[] args) {
        Contact1 c1=new Contact1("zzz","mail1@gmail.com",2424342);
        Contact1 c2=new Contact1("bbb","mail2@gmail.com",2424342);
        Contact1 c3=new Contact1("ccc","mail3@gmail.com",2424342);
        ArrayList<Contact1> al=new ArrayList<Contact1>();
        al.add(c1);
        al.add(c2);
        al.add(c3);
        Collections.sort(al, new MyComparator());
        for (Contact1 contact : al) {
            System.out.println(contact);
        }
    }
}

Regular Expressions in java


Regular expressions defines the rule or pattern for the string litral. These rule can check the strings for common characteriscs to be followed by all string literal. For example email string must contain @ sybol and the rule for this may be ".+@." . Regular expression is used to express the some portion or structure of the strings.

Use of Regular expression
  • to search string in paragraph or line.
  • to edit the specific portion of test into paragraph
  • to validate the string
  • to specified the rules for the server rewrite
In java programming languge you can use java.util.regex API to working with regular expressions. this API provides all supported class to use the regular expresion into you project. in the java.util.reges API, there are three classes to be used to deal with regular expression. Pattern class is used to create the object that is the compliled representtation of reqular expression specified by you. Matcher class's object work as the interpretor for the reqular expression that process the input string againt the pattern.PatternSyntaxException object is used to represent unchecked exception for the syntax error in regular expresion patttern.
for example

Pattern p = Pattern.compile("a*b");

It creates the pattern object that represents the reqular expresion a*b and Pattern class doesn't provides public constructor to crate the object but it has static method compile to be used to create the Pattern object .
 
Matcher m = p.matcher("aaaaab");
Pattern object has the matcher method that return the Matcher object for the specified string passed as argument.
 
boolean b = m.matches();

Matches method return the boolean values indicating wwhether string passed to macther is following the rule contain in pattern.

For details , see here  : http://download.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html





Searching for string
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class RegexTest1 {

    public static void main(String[] args){
            //pass the pattern to be searched 
            Pattern pattern = Pattern.compile("@");
            // pass the string in which you want to search above pattern
            Matcher matcher = pattern.matcher("hello dear, my email address is user@mydomain.com.");
            while (matcher.find()) {
                System.out.println("Found : "+matcher.group()+", starting at "+matcher.start()+" and ending at "+matcher.end());
            }
           
        }
}




Replacing found expression
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class RegexTest2 {

    public static void main(String[] args) {
        // pass the pattern to be searched
        Pattern pattern = Pattern.compile("user");
        // pass the string in which you want to search above pattern
        Matcher matcher = pattern
                .matcher("hello user, welcome to your account.");
        
        String resultString = matcher.replaceAll("Hemraj");
        System.out.println(resultString);
    }
}


Replacing found expression
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class RegexTest3 {

    public static void main(String[] args) {
        // pass the pattern to be searched
        Pattern pattern = Pattern.compile("o");
        // pass the string in which you want to search above pattern
        Matcher matcher = pattern
                .matcher("http://www.domain.co.in/contactus.jsp");
        while (matcher.find()) {
            System.out.println("Found : "+matcher.group()+", starting at "+matcher.start()+" and ending at "+matcher.end());
        }
        String resultString = matcher.replaceAll("newdomain.com");
        System.out.println(resultString);
    }
}



Popular Posts