Wednesday, December 30, 2009

Java String array - Single and Multidimensional

In java arrays can be single as well as multi dimentional. This is true not only for Strings, but also for int, double, char etc all datatypes.
Arrays can be declared in two ways. Today i will show you how to declare arrays in Java.
This post will cover both the ways array can be declared and also how to access the elements.
Please comment if this post helps you or if there is something I missed.
Happy Coding.

Lets start with Single Dimension Arrays:





 String [] OneDArray1 = new String[10];
  OneDArray1[0] = "1";
  OneDArray1[2] = "2";
  OneDArray1[5] = "3";

  for(int i=0;i
   System.out.println(OneDArray1[i]);
  }
  
Output of this code snippet:

 1
 null
 2
 null
 null
 3
 null
 null
 null
 null



Another way of declaring single dimension arrays:


 String [] OneDArray2 = {"1","2","3"};
  
  for(int i=0;i
   System.out.println(OneDArray2[i]);
  }
  
Output of this code snippet:

 1
 2 
 3
 

Multi Dimensional Arrays


  String TwoDArray1[][] = new String[2][3];
  
  TwoDArray1[0][0] = "1";
  TwoDArray1[0][1] = "2";
  TwoDArray1[0][2] = "3";
  
  TwoDArray1[1][0] = "4";
  TwoDArray1[1][1] = "5";
  TwoDArray1[1][2] = "6";
  
  for(int i=0;i
   for(int j=0;j
    System.out.println(TwoDArray1[i][j]);
   }
  }

Output of this code snippet:

 1
 2
 3
 4
 5
 6
 

Another way of declaring multi dimensional arrays:


 String TwoDArray2[][] = { {"1","2"},{"3","4"} };
  
  for(int i=0;i
   for(int j=0;j
    System.out.println(TwoDArray2[i][j]);
   }
  }
 
Output of this code snippet:
 1
 2
 3
 4



Friday, December 18, 2009

Java find longest matching part or substring of string

Finding largest common sub string from an array of strings is often very useful. Recently I had this requirement, where I was trying to exclude a list of strings by using regex patterns. For this I had to find the greatest matching substring among the strings, so that I put that substring as a regex, and save a lot of effort.
Unfortunately I didn't find any ready made code on the net, that does the same thing. So I wrote my own.

I tried to make the logic as optimum as possible.
If anyone has a better algorithm in mind, please share it with me.

I have used a custom string length comparator, so optimise the string traversing. Readers can write their own implementation of the comparator, or copy my custom string length comparator class from here.



 import java.util.Arrays;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.Set;
 import java.util.TreeSet;

 public class SubString {

  public static void main(String[] args) {
    String [] strs = {
     "this is a very big first string which should be processed at last",
     "this is a very small string" ,
     "this is a very boring string nothing special",
     "this is a very simple yet bigger string, second large"
    };

   //Arrays.sort(strs, new CustomStringLengthComparator());
   String sub = strs[0];
   Map subStrings = new HashMap();
   int j=strs[0].length();

   String comparingString =strs[1];
   while (j>=0) {
    for(int i=0;i< j;i++) {
     sub = strs[0].substring(i, j);
     if (comparingString.contains(sub)) {
      subStrings.put(sub.length(),sub);
     }
    }
    j--;
   }
   boolean flag =false;
   if(!subStrings.isEmpty()) {
    Set set = subStrings.keySet();
    TreeSet treeSet = new TreeSet(set);     
    String matchedString = subStrings.get(treeSet.last());   
    for(int k=2;k
     if (strs[k].contains(matchedString)) {
      flag=true;     
     }else {
      flag=false;     
      break;     
     }   
    }     
    if (flag) { 
     System.out.println("Matched : " + subStrings.get(treeSet.last()));
    }else {       
     System.out.println("No Match");     
    }   
   } 
  } 
 }

Custom String Length Comparator Java

The default sort method for strings is Java is it's character values. For example, If we have a string array:



String [] strs = {"abc", "xyz", "mnop123"};
And we use Arrays.sort(strs), the output will be in the following order:


abc
mnop123
xyz
But there are times, when we want to sort strings, by their length. The following custom string length comparator will serve the purpose:


import java.util.Comparator;

public class CustomStringLengthComparator implements Comparator{

 public int compare(String o1, String o2) {
  if (o1.length() < o2.length()) {
        return -1;
      } else if (o1.length() > o2.length()) {
        return 1;
      } else {
        return 0;
      }
 }

}


Instead of using


Arrays.sort(strs)
we have to use


Arrays.sort(strs, new CustomStringLengthComparator());



Wednesday, December 9, 2009

Currency format

As we know the way of formatting currency are different in many country. Main there is a big difference in European and British way. This code snippet converts the currency to appropriate formats and also does the reverse parsing.



 
public static void main(String args[]){
  // Format
     Locale locale = Locale.FRANCE;
     String string1 = NumberFormat.getCurrencyInstance(locale).format(123456789.12);
     System.out.println(string1);
    
     locale = Locale.US;
     String string = NumberFormat.getCurrencyInstance(locale).format(123456789.12);
     System.out.println(string);
    
     // Parse
     try {
         Number number = NumberFormat.getCurrencyInstance(locale).parse(string1);
         System.out.println(number.toString());
         number = NumberFormat.getCurrencyInstance(locale).parse(string);
         System.out.println(number.toString());
     } catch (ParseException e) {
     }
 }
 
 

List The Contents of a ZIP File

This is a utility program to view the contents of a zip file


import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 *
 * @author Rakesh P
 * ZipFile Function Accept the Path of the Zip File 
 */
public class ZipContents{
   
    public void listContentsOfZipFile() {
       
        try {
            ZipFile zipFile = new ZipFile("d:/FeedtoInterfaces.zip");
           
            Enumeration zipEntries = zipFile.entries();
           
            while (zipEntries.hasMoreElements()) {
               
                //Process the name, here we just print it out
                System.out.println(((ZipEntry)zipEntries.nextElement()).getName());
               
            }
           
        } catch (IOException ex) {
            ex.printStackTrace();
        }
       
    }
   
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       
        new  ZipContents().listContentsOfZipFile();
       
    }
}