Friday, May 13, 2011

Remove Duplicates in Java

Description:
You have an ArrayList with duplicates, and you need to remove them


Solution:

  • Create a HashSet with the ArrayList as the constructor argument:

    HashSet hashSet = new HashSet(myArrayList);
  • If the order is important, use a LinkedHashSet:

    LinkedHashSet  linkedHashSet = new LinkedHashSet(myArrayList);
  • Use the following method to remove duplcates:
    static ArrayList deDupKeepingFirst(ArrayList withDups,
      Comparator comparator,boolean presorted) {
     if (!presorted) {
      Collections.sort(withDups, comparator);
     }
     int size = withDups.size();
    
     ArrayList result = new ArrayList(size);
     if (size <= 1) {
      if (size == 1) {
       result.add(withDups.get(0));
      }
      return result;
     }
     Object prev = withDups.get(0);
     result.add(prev);
    
     for (int i = 1; i < size; i++) {
      Object o = withDups.get(i);
      if (comparator.compare(o, prev) != 0) {
       result.add(o);
       prev = o;
      }
      else
       System.out.println(o.toString());
     }
     return result;
    }
    
    private static class StringComp implements Comparator
    {
     public int compare(Object o1, Object o2)
     {
      return o1.toString().compareToIgnoreCase((o2).toString());
     }
    }
    

Sorting ArrayLists in Java

Description:
You have an ArrayList of objects that you need to be sorted by their
integer member variables

Solution:

Let's say you have a Record class with the following members: int id, int weight;
class Record {
 public Record(int i, int w){
  this.id =i;
  this.weight = w;
 }
 int id;
 int weight;

 public int getId() {
  return id;
 }
 public int getWeight() {
  return weight;
 }
}

You have an ArrayList of objects of the Record class that need to be sorted by weight. To make it possible, the Record class needs to implement the Comparable interface which mandates the use of the compareTo method with the following signature:
public int compareTo(Object o)

That means we need to add the following code to the Record class:

public int compareTo(Object o) {
 int weight = ((Record) o).getWeight();
 return weight - this.weight;
}

We use weight - this.weight for descending order and
this.weight - weight for ascending order.

Once we have the proper method in the Record class, all we need to do is use the sort method
of the Collections class.

Collections.sort (myArrayList);

Tuesday, May 25, 2010

Determine the Next Month in Java

First, get an instance of the Calendar class:

Calendar cal = GregorianCalendar.getInstance();
Declare a format to be used:
SimpleDateFormat df = new SimpleDateFormat("MMM yyyy");

Set the Calendar's current time to today's Date:

cal.setTime(new Date());

Add a month to the Calendar's date:

cal.add(Calendar.MONTH, 1);

Format the new date into a string:

String nextMonth = df.format(cal.getTime());

The nextMonth String will contain the next month's value.

The following technique allows us to show 12 consecutive months:

cal.setTime(new Date());
for(int i=0; i<12;i++){
   cal.add(Calendar.MONTH, 1);
   String nextMonth = df.format(cal.getTime());
   System.out.println(nextMonth);
}


The Calendar class has a lot of other methods to set its date. For example, you can set the year and month as follows:

cal.set(Calendar.YEAR, 2010);
cal.set(Calendar.MONTH, 05);
or
cal.set(Calendar.MONTH, Calendar.JUNE);

This code sets the Calendar date to June 2010.

You can also set the date using year, month, and day arguments.

cal.set(2010, 05, 15);

This code sets the Calendar date to June 15, 2010.

Monday, May 24, 2010

Enumerate All Keys of a Hashtable


Set keys = myHashTable.keySet();
Iterator iter = keys.iterator();
while (iter.hasNext())
{
    Object key = iter.next();
    System.out.println("key:"+ (String)key);
}

A Simple Way to Find Data in XML Using dom4j

dom4j is a small but powerful package to parse XML documents. It has the advantage of having a very small footprint and being very easy to use. The dom4j website has a lot of examples that show how to use it.
If you have a simple xml file like the following one, I will show you how to use dom4j to find data.

<?xml version="1.0"?>
<students>
        <student>
                <name>Mike</name>
                <course>JSP</course>
        </student>
        <student>
                <name>Janet</name>
                <course>EJB</course>
        </student>
</students>

The file name is students.xml.
Suppose, you need to find the course for a student named Mike.
First, you need to parse a document:

public Document parse(String file) throws DocumentException {
    SAXReader reader = new SAXReader();
    Document document = reader.read(file);
    return document;
}

Document doc= parse("students.xml"); 

Then, use the following statement:
String course = doc.valueOf("//student[name='Mike']/course");  
This statement uses an XPath Engine library from Jaxen which means you need to have it in your classpath.
If you want to limit your library usage to dom4j proper you'll have to write your own method which may look like the following:

public String findStudentCourse(Document doc, String studentName) {
    Element root = doc.getRootElement();
    for (Iterator i = root.elementIterator(); i.hasNext();) {
        Element el = (Element) i.next();
        if (el.elementText("name").equals(studentName)) {
            return el.elementText("course");
        }
    }
    return null;
}
If you want to iterate through all the student elements and print the name-course combinations use the following example:

Element root = document.getRootElement();
for (Iterator i = root.elementIterator(); i.hasNext();) {
    Element el = (Element) i.next();
    System.out.println("Child Element Path :" + el.getPath());
    System.out.println("    Name:" + el.elementText("name"));
    System.out.println("    Course:" + el.elementText("course"));
}

Convert Collection to Array

The following example converts an ArrayList into an array of strings:

    ArrayList al = new ArrayList();
    //Fill the array 
    ...........

    String[] aStrings = (String[]) al.toArray(new String[0]);

Find and Replace All Occurrencies of a String

Description:
You need to replace all occurencies of a string in a text file

Solution: (For Java 1.4 and higher) '

public static void readReplace(String fname, String oldPattern, String replPattern){
    String line;
    StringBuffer sb = new StringBuffer();
    try {
        FileInputStream fis = new FileInputStream(fname);
        BufferedReader reader=new BufferedReader ( new InputStreamReader(fis));
        while((line = reader.readLine()) != null) {
            line = line.replaceAll(oldPattern, replPattern);
            sb.append(line+"\n");
        }
        reader.close();
        BufferedWriter out=new BufferedWriter ( new FileWriter(fname));
        out.write(sb.toString());
        out.close();
    }
    catch (Throwable e) {
                System.err.println("*** exception ***");
    }
}