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

Tuesday, May 27, 2014

Wednesday, December 11, 2013

Java: intersect two arrays


int a[] = {3, 10, 4, 2, 8};
int[] b = {10, 4, 12, 3, 23, 1, 8};
List<Integer> aList =  Arrays.asList(a);
List<Integer> bList =  Arrays.asList(b);
aList.retainsAll(bList);
System.out.println(" a intersection b "+aList);

Reference:
http://stackoverflow.com/questions/12919231/finding-the-intersection-of-two-arrays

Friday, August 23, 2013

Java Sockets: Simple client and server example source files

The explanation of the source code is here:
http://docs.oracle.com/javase/tutorial/networking/sockets/

You can donwload the source code here
http://www.oracle.com/technetwork/java/javase/downloads/java-se-7-tutorial-2012-02-28-1536013.html

1. Download and unzip the javatutorials.zip file
2. Go to \javatutorials\tutorial\networking\sockets\examples

Now you can access the source files to run the example.



Sunday, August 4, 2013

Java: Simple sample of socket server using InetAddress

public static void main(String[] args) {
        // TODO code application logic here
        String hostIP = "127.0.0.1";
        InetAddress bindAddr; 
        try {
            bindAddr = InetAddress.getByName(hostIP);
            launchServerSocket(4567, 4568, bindAddr );
        } catch (UnknownHostException e) {
            System.out.println("Unknown Host: " + hostIP);
            e.printStackTrace(); 
        }                
    }
 
    public static void launchServerSocket(int portNumber, int backlog, InetAddress bindAddr ){
        try {
            ServerSocket serverSocket = new ServerSocket(portNumber, backlog, bindAddr);
            System.in.read();// prevent console to be closed
        } 
        catch (IOException e) {
            System.out.println("Could not listen on port: " + portNumber);
            e.printStackTrace();            
        }
    }

Tuesday, May 28, 2013

Java: convert from Long milliseconds to calendar object

Long myLong = entity.getPurchaseOrderDateMilliseconds();// returns 1369717200000
Timestamp timestamp = new Timestamp(myLong);
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTimeInMillis(timestamp.getTime());        

Friday, November 2, 2012

Sunday, October 7, 2012

Java: Converting Jsontext to JavaObject

Look at this great sample:


import java.util.List;
import com.google.gson.Gson;

public class Test {

    public static void main(String... args) throws Exception {
        String json = 
            "{"
                + "'title': 'Computing and Information systems',"
                + "'id' : 1,"
                + "'children' : 'true',"
                + "'groups' : [{"
                    + "'title' : 'Level one CIS',"
                    + "'id' : 2,"
                    + "'children' : 'true',"
                    + "'groups' : [{"
                        + "'title' : 'Intro To Computing and Internet',"
                        + "'id' : 3,"
                        + "'children': 'false',"
                        + "'groups':[]"
                    + "}]" 
                + "}]"
            + "}";

        // Now do the magic.
        Data data = new Gson().fromJson(json, Data.class);

        // Show it.
        System.out.println(data);
    }

}

class Data {
    private String title;
    private Long id;
    private Boolean children;
    private List<Data> groups;

    public String getTitle() { return title; }
    public Long getId() { return id; }
    public Boolean getChildren() { return children; }
    public List<Data> getGroups() { return groups; }

    public void setTitle(String title) { this.title = title; }
    public void setId(Long id) { this.id = id; }
    public void setChildren(Boolean children) { this.children = children; }
    public void setGroups(List<Data> groups) { this.groups = groups; }

    public String toString() {
        return String.format("title:%s,id:%d,children:%s,groups:%s", title, id, children, groups);
    }
}

Reference:
http://stackoverflow.com/questions/1688099/converting-json-to-java/1688182#1688182

Saturday, February 4, 2012

Java: Exception in thread main java.lang.NoClassDefFoundError

Try doing the following steps:

1. Set the CLASSPATH to the location of the folder where you have saved the .java files.
2. Make sure that in the PATH, you got a setting describing where the installation files are- i.e C:\Program Files\javajdk 1.6.0_18\bin.
3. Create/Verify a variable called JAVA_HOME containing the location for the jdk bin. I.E C:\Program Files\javajdk 1.6.0_18

Note: Be aware of close an reopen the console to load the changes of your path

Reference:
http://www.tech-recipes.com/rx/826/java-exception-in-thread-main-javalangnoclassdeffounderror/

Monday, November 14, 2011

Java: Copying and Cloning Lists: public Object clone()

import java.util.ArrayList;
import java.util.List;

public class MainClass {
  public static void main(String[] a) {

    List list = new ArrayList();
    list.add("A");

    List list2 = ((List) ((ArrayList) list).clone());

    System.out.println(list);
    System.out.println(list2);

    list.clear();

    System.out.println(list);
    System.out.println(list2);
  }
}

Source:

Thursday, October 20, 2011

Thursday, September 8, 2011

Java: Iterate a String


java.text.CharacterIterator;
java.text.StringCharacterIterator;
CharacterIterator it = new StringCharacterIterator("abcd");

// Iterate over the characters in the forward direction
for (char ch=it.first(); ch != CharacterIterator.DONE; ch=it.next()) {
    // Use ch ...
}
Reference:
http://www.exampledepot.com/egs/java.text/StrIter.html

Wednesday, September 7, 2011

Java: replace chars in String

/*
        Replaces all occurrences of given character with new one
        and returns new String object.
*/

String returnString = "test string to do some change";
returnString = returnString.replace( 'o', 'd' );

Source:
http://www.javadeveloper.co.in/java-example/java-string-replace-example.html
http://javarevisited.blogspot.com/2011/12/java-string-replace-example-tutorial.html
References:
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html

Java : Using currency format

// Using currency notations i.e. Colombian Currency
public String FormateoValor(Double valor){
NumberFormat n = NumberFormat.getCurrencyInstance(new Locale("es", "CO")); 
String returnString = n.format(valor.doubleValue());
return returnString ;  
}


References:
http://www.javaworld.com/javaworld/jw-06-2001/jw-0601-cents.html
http://www.herongyang.com/JDK/Locale-java-util-Local-Localization.html

Tuesday, September 6, 2011

Java: convert String to Long and vice versa

// String to long
long l = Long.parseLong(str);

// long to string
String numCadena= String.valueOf(l);

Sources:
http://www.java-tips.org/java-se-tips/java.lang/conversion-from-string-to-long.html
http://www.java-examples.com/java-string-valueof-example

Java: convert String to int and vice versa


// string to int
int numEntero = Integer.parseInt(numCadena);

// int to String
String numCadena= String.valueOf(numEntero);

Source:
http://emilio.aesinformatica.com/2007/11/22/pasar-de-int-a-string-y-de-string-a-int-en-java/

Wednesday, August 10, 2011

Java: String trim method


import java.lang.*;

public class StringTrim{
  public static void main(String[] args) {
  System.out.println("String trim example!");
  String str = " RoseIndia";
  System.out.println("Given String :" + str);
  System.out.println("After trim :" +str.trim());
  }
}

Output:


String trim example!
Given String :  RoseIndia
After trim :RoseIndia


Source:
http://www.roseindia.net/java/beginners/StringTrim.shtml

Tuesday, August 2, 2011

Java: iterate List


          String sArray[] = new String []{"Array 1", "Array 2", "Array 3"};

 //convert array to list
 List lList = Arrays.asList(sArray);

          //iterator loop
 Iterator<String> iterator = lList.iterator();
 while ( iterator.hasNext() ){
     System.out.println( iterator.next() );
 }

          //for loop
 for (int i=0; i< lList.size(); i++)
 {
 System.out.println( lList.get(i) );
 }

          //while loop
 int j=0;
 while (j< lList.size())
 {
 System.out.println( lList.get(j) );
 j++;
 }
Source:
http://www.mkyong.com/java/how-do-loop-iterate-a-list-in-java/

Java: iterate info from ResultSet


ResultSet rs = stmt.executeQuery(query);
      ResultSetMetaData rsmd = rs.getMetaData();

      PrintColumnTypes.printColTypes(rsmd);
      System.out.println("");

      int numberOfColumns = rsmd.getColumnCount();

      for (int i = 1; i <= numberOfColumns; i++) {
        if (i > 1) System.out.print(",  ");
        String columnName = rsmd.getColumnName(i);
        System.out.print(columnName);
      }
      System.out.println("");

      while (rs.next()) {
        for (int i = 1; i <= numberOfColumns; i++) {
          if (i > 1) System.out.print(",  ");
          String columnValue = rs.getString(i);
          System.out.print(columnValue);
        }
        System.out.println("");
      }

Source:
http://www.java2s.com/Code/Java/Database-SQL-JDBC/Outputdatafromtable.htm

Wednesday, May 18, 2011

Java: convert array of integers to Integer Array List an viceversa

//  convert array of integers to Integer Array List
public ArrayList<Integer> convertToIntegersArrayList(int[] mensaje)
    {
        ArrayList<Integer> returnArray = new ArrayList<Integer>();      
        for (int i=0; i < mensaje.length; i++)
        {
            returnArray.add((Integer)mensaje[i]);
        }
        return returnArray;
    }

//  convert  Integer Array List  to array of integers
public int[] convertToArrayOfIntegers(ArrayList<Integer> integers)
    {
        int[] ret = new int[integers.size()];
        for (int i=0; i < ret.length; i++)
        {
            ret[i] = integers.get(i).intValue();
        }
        return ret;
    }