Header Ad

Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Monday, April 2, 2012

Java ArrayList - Sorting List of Objects in Java

We can sort list of Objects in java using Comparators and Comparable. What are these?

Comparable is an interface that is implemented by a class of Object that have to be sorted.

java.lang.Comparable: int CompareTo(Object obj1)
This method will compare this object with obj1 object. Returns int value as follows.

1. positive - this object is greater than obj1
2. zero - this object equals to obj1
3. negative - this object is smaller than obj1

Comparator : Comparator is mainly used to override compare. Comparable will provide an ability to sort of any type of Collection.

java.util.Comparator: int compare(Object o1, Objecto2) This method compares o1 and o2 objects. Returned int value has the following meanings.

1. positive – o1 is greater than o2
2. zero – o1 equals to o2
3. negative – o1 is less than o1
The following is the Student class.

public class Student
{
int rollNo;
String name;
 
public Student(int rollNo, String name)
{
this.rollNo = rollNo;
this.name = name;
}

public void setRollNo(int rollNo)
{
this.rollNo = rollNo;
}

public int getRollNo()
{
return this.rollNo;
}
public void setName(String name)
{
this.name = name;
}

public String getName()
{
return this.name;
}
 }

The following is the "students" List collection.
Stundent std1 = new Stundent(1, "Vinay");
Stundent std2 = new Stundent(2, "Kumar");
Stundent std3 = new Stundent(3,"Goyal");
Stundent std4 = new Stundent(4,"Sharma");

ArrayList students = new ArrayList();
students.add(std1);
students.add(std2);
students.add(std3);
students.add(std4);

The following is the sample code to sort an arraylist in java.

java.util.Collections.sort(students, new Comparator<Student>()
{
    public int compare(Student std1, Student std2) {
       return std1.getName().compareToIgnoreCase(std2.getName());
    }
});


Sunday, April 1, 2012

Concatenation of String array to String

This program will help to concatenate String array to a simple string with a delimiter( if require).

public class StrArrtoStr {

public static void main(String[] args) {
String weeks_days[] = new String[7];
weeks_days[0] = "Sunday";
weeks_days[1] = "Monday";
weeks_days[2] = "Tuesday";
weeks_days[3] = "Wednesday";
weeks_days[4] = "Thursday";
weeks_days[5] = "Friday";
weeks_days[6] = "Saturday";
StringBuffer finalString = new StringBuffer();

if (weeks_days.length > 0) {
finalString.append(weeks_days[0]);
for (int i = 1; i < weeks_days.length; i++) {
finalString.append(",");
finalString.append(weeks_days[i]);
}
}

System.out.println("Concatenation of String array to String:::"
+ finalString.toString());

}

}

In the above example, we have String array of length 7 having items(weeks). We need to concatenate all these into a one string.

The above program will provide a final output which is as follows:
Concatenation of String array to String::: Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday

Tuesday, June 15, 2010

Parsing XML string or content using java code

The following program is an example for parsing the XML string using code.

import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class XMLParse {
  public static void main(String arg[]) throws Exception{
    String xmlRecords = "A"
        "";

    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xmlRecords));

    Document doc = db.parse(is);
    NodeList nodes = doc.getElementsByTagName("employee");

    for (int i = 0; i < nodes.getLength(); i++) {
      Element element = (Elementnodes.item(i);

      NodeList name = element.getElementsByTagName("name");
      Element line = (Elementname.item(0);
      System.out.println("Name: " + getCharacterDataFromElement(line));

      NodeList title = element.getElementsByTagName("title");
      line = (Elementtitle.item(0);
      System.out.println("Title: " + getCharacterDataFromElement(line));
    }

  }

  public static String getCharacterDataFromElement(Element e) {
    Node child = e.getFirstChild();
    if (child instanceof CharacterData) {
      CharacterData cd = (CharacterDatachild;
      return cd.getData();
    }
    return "";
  }
}

Wednesday, May 12, 2010

Reading CSV using java program

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.StringTokenizer;

public class ReadCSV {

//readCSV class starts here

public static void main(String args[]) throws IOException

{ //main method starts

String fName = "test1.csv";//csv file which u wanna read

String thisLine; //string variable which take each record at a time

int count=0; //to count no. of records

FileInputStream fis = new FileInputStream(fName);
//A FileInputStream obtains input bytes from a file in a file system

DataInputStream myInput = new DataInputStream(fis);
/*data input stream lets an application read primitive Java data types
from an underlying input stream in a machine-independent way*/

while ((thisLine = myInput.readLine()) != null)
{ //beginning of outer while loop
StringTokenizer st =new StringTokenizer(thisLine,",");
while(st.hasMoreElements()){
String field = st.nextToken();
System.out.print(field+", ");
}
System.out.println();

} //ending of outer while loop
} //main method ends
} //readCSV class ends here

Tuesday, April 27, 2010

How to resize an image in JAVA or Thumbnail creation in Java

package com.jiva.bean.javabeans;
import java.awt.Image;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import javax.swing.ImageIcon;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import java.awt.Container;
import java.awt.MediaTracker;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.io.BufferedOutputStream;
import com.sun.image.codec.jpeg.JPEGEncodeParam;

public class ImageResize
{
int setWidth;
int setHeight;
com.jiva.application.auth.AppSession appSession;
public void setWidth(int width)
{
setWidth=width;
}
public void setHeight(int height)
{
setHeight=height;
}

public String imageProps(String path) throws FileNotFoundException, IOException
{
File source=new File(path);
Image inImage = new ImageIcon(source.getAbsolutePath()).getImage();
int imageWidth=inImage.getWidth(null);
int imageHeight=inImage.getHeight(null);
inImage.flush();
int returnImageWidth=setWidth;
int returnImageHeight=setHeight;
double ReturnImageRatio = (double)returnImageWidth/ (double)returnImageHeight;
double ImageRatio = (double)imageWidth / (double)imageHeight;
if (ReturnImageRatio < ImageRatio)
{
returnImageHeight = (int)((double)returnImageWidth / ImageRatio);
}
else
{
returnImageWidth = (int)((double)returnImageHeight * ImageRatio);
}
String x=Integer.toString(returnImageWidth)+"."+Integer.toString(returnImageHeight);

return x;
}
public void createThumbnail(String imgFilePath,String thumbPath,int thumbWidth,int thumbHeight)throws Exception{

Image image = Toolkit.getDefaultToolkit().getImage(imgFilePath);
MediaTracker mediaTracker = new MediaTracker(new Container());
mediaTracker.addImage(image, 0);
mediaTracker.waitForID(0);
double thumbRatio = (double)thumbWidth / (double)thumbHeight;
int imageWidth = image.getWidth(null);
int imageHeight = image.getHeight(null);
double imageRatio = (double)imageWidth / (double)imageHeight;
if (thumbRatio < imageRatio) {
thumbHeight = (int)(thumbWidth / imageRatio);
} else {
thumbWidth = (int)(thumbHeight * imageRatio);
}
BufferedImage thumbImage = new BufferedImage(thumbWidth,
thumbHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = thumbImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(thumbPath));
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.
getDefaultJPEGEncodeParam(thumbImage);
int quality = 100;
param.setQuality((float)quality / 100.0f, false);
encoder.setJPEGEncodeParam(param);
encoder.encode(thumbImage);
out.close();
}
public static void main(String args[])
{
try{
ImageResize resize=new ImageResize();
resize.createThumbnail("D:/Photos/1/original.jpg", "D:/Photos/1/original_resize.jpg", 70, 70);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Random Password Generation in Java

The following program will generate the random password.

import java.util.Random;
public class AutoPwdGenerator {

public String gen8DigitPwd()
{
String strPassword="";
try{
Random randomPassword = new Random();
int i=randomPassword.nextInt(10);
int j = randomPassword.nextInt(100);
int k = randomPassword.nextInt(100);
int l = randomPassword.nextInt(10);
int m = randomPassword.nextInt(10);
strPassword=i+"T"+j+k+"P"+l;
System.out.println("Auto generated password"+strPassword);

}catch(Exception e)
{
e.printStackTrace();
}
return strPassword;
}

}

public class AutoPwdGeneratorTest
{
public static void main(String args[])
{
AutoPwdGenerator autoGen = new AutoPwdGenerator();
String randomPwd = autoGen.gen8DigitPwd();
System.out.println("Generated Random Password:"+randomPwd);
}

}