Monday, April 28, 2014

Using Collections.sort() with Comparator to sort ArrayList

Person.java
package javapeople;

public class Person {

    private String surname;
    private String name;

    public Person(String name, String surname) {
        this.surname = surname;
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }
    
    public String getName() {
        return name;
    }

    public String toString() {
        return name + " " + surname;
    }

}

SortBySurname.java
package javapeople;

import java.util.Comparator;

public class SortBySurname implements Comparator <Person> {

    @Override
    public int compare(Person o1, Person o2) {
        return o1.getSurname().compareTo(o2.getSurname());
    }
    
}

SortByName.java
package javapeople;

import java.util.Comparator;

public class SortByName implements Comparator <Person>{

    @Override
    public int compare(Person o1, Person o2) {
        return o1.getName().compareTo(o2.getName());
    }
    
}

JavaPeople.java
package javapeople;

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

/**
 * @web java-buddy.blogspot.com
 */
public class JavaPeople {

    public static void main(String[] args) {
        ArrayList<Person> peopleList = new ArrayList<>();
        peopleList.add(new Person("Albert", "Einstein"));
        peopleList.add(new Person("Isaac", "Newton"));
        peopleList.add(new Person("Thomas", "Edison"));
        peopleList.add(new Person("Charles", "Darwin"));
        peopleList.add(new Person("James", "Watt"));
        
        System.out.println("Unsorted:");
        System.out.println(peopleList);
        
        Collections.sort(peopleList, new SortBySurname());
        System.out.println("Sorted by Surname:");
        System.out.println(peopleList);
        
        Collections.sort(peopleList, new SortByName());
        System.out.println("Sorted by Name:");
        System.out.println(peopleList);
    }

}


Sunday, April 27, 2014

Get information about Exception, with toString(), getMessage() and printStackTrace()

This example get details of Exception with toString(), getMessage() and printStackTrace().


package javadisplayexception;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaDisplayException {

    public static void main(String[] args) {
        
        try{
            int i = 10/0;
        }catch (Exception ex){
            System.out.println("- ex.toString() -");
            System.out.println(ex.toString());
            System.out.println();
            System.out.println("- ex.getMessage() -");
            System.out.println(ex.getMessage());
            System.out.println();
            System.out.println("- ex.printStackTrace() -");
            ex.printStackTrace();
        }
        
    }
    
}

Example of using Variable Length Arguments

Example to implement and call method with Variable Length Arguments.

package javavariablelengtharguments;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaVariableLengthArguments {

    public static void main(String[] args) {
        printAll(1, 2, 3, 4, 5, 6);
        System.out.println("average= " + average(1, 2, 3, 4, 5, 6));
    }
    
    static void printAll(int... num){
        for(int n : num){
            System.out.println(n);
        }
    }
    
    static float average(int... num){
        float total = 0;
        for(int i=0; i<num.length; i++){
            total+=num[i];
        }
        return total/num.length;
    }
    
}



Thursday, April 24, 2014

Java 8 Pocket Guide

Java 8 Pocket Guide

When you need quick answers for developing or debugging Java programs, this pocket guide provides a handy reference to standard features of the Java programming language and its platform. You’ll find helpful programming examples, tables, figures, and lists, as well as Java 8 features such as Lambda Expressions and the Date and Time API. It’s an ideal companion, whether you’re in the office, in the lab, or on the road.

This book also provides material to help you prepare for the Oracle Certified Associate Java Programmer exam.

  • Quickly find Java language details, such as naming conventions, types, statements and blocks, and object-oriented programming
  • Get details on the Java SE platform, including development basics, memory management, concurrency, and generics
  • Browse through information on basic input/output, NIO 2.0, the Java collections framework, and the Java Scripting API
  • Get supplemental references to fluent APIs, third-party tools, and basics of the Unified Modeling Language (UML)

Saturday, April 19, 2014

Functional Programming in Java: Harnessing the Power Of Java 8 Lambda Expressions

Intermediate level, for programmers fairly familiar with Java, but new to the functional style of programming and lambda expressions.

Functional Programming in Java: Harnessing the Power Of Java 8 Lambda Expressions

Get ready to program in a whole new way. Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that's also a breeze to parallelize. You'll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You'll design and write applications better using the new standards in Java 8 and the JDK.

Lambda expressions are lightweight, highly concise anonymous methods backed by functional interfaces in Java 8. You can use them to leap forward into a whole new world of programming in Java. With functional programming capabilities, which have been around for decades in other languages, you can now write elegant, concise, less error-prone code using standard Java. This book will guide you though the paradigm change, offer the essential details about the new features, and show you how to transition from your old way of coding to an improved style.

In this book you'll see popular design patterns, such as decorator, builder, and strategy, come to life to solve common design problems, but with little ceremony and effort. With these new capabilities in hand, Functional Programming in Java will help you pick up techniques to implement designs that were beyond easy reach in earlier versions of Java. You'll see how you can reap the benefits of tail call optimization, memoization, and effortless parallelization techniques.

Java 8 will change the way you write applications. If you're eager to take advantage of the new features in the language, this is the book for you.

What you need:
Java 8 with support for lambda expressions and the JDK is required to make use of the concepts and the examples in this book.

Thursday, April 17, 2014

Some examples of using Stream of Java 8

This post show some example of using Stream<String> of Java 8; such as splite String to Stream<String> of words, print all element in Stream, count number of element, sort Stream, convert to lower case, find the maximum, and Find the first word starts with.

package java8stream;

import java.util.Optional;
import java.util.stream.Stream;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class Java8Stream {

    static String lyrics = "Hello darkness, my old friend,\n"
            + "I've come to talk with you again,\n"
            + "Because a vision softly creeping,\n"
            + "Left its seeds while I was sleeping,\n"
            + "And the vision that was planted in my brain\n"
            + "Still remains\n"
            + "Within the sound of silence.";

    public static void main(String[] args) {
        System.out.println("--- lyrics ---");
        System.out.println(lyrics);

        System.out.println("--- Some examples of using Stream ---");
        
        //print all element in Stream<String>
        Stream.of(lyrics.split("[\\P{L}]+"))
            .forEach((String element) -> System.out.println(element));
        
        //count number of element in Stream
        System.out.println("count of words = " + 
            Stream.of(lyrics.split("[\\P{L}]+")).count());
        
        System.out.println("--- Sorted Stream ---");
        Stream<String> sortedStream = Stream.of(lyrics.split("[\\P{L}]+")).sorted();
        sortedStream.forEach((String element) -> System.out.println(element));
        
        System.out.println("--- Convert to lower case ---");
        Stream<String> sortedStreamLower = Stream.of(lyrics.split("[\\P{L}]+"))
                .map(String::toLowerCase);
        sortedStreamLower.forEach((String element) -> System.out.println(element));
        
        System.out.println("--- Find the maximum, ignore case, in Stream<String> ---");
        Optional<String> max = Stream.of(lyrics.split("[\\P{L}]+"))
                .max(String::compareToIgnoreCase);
        if(max.isPresent()){
            System.out.println("max = " + max.get());
        }
        
        System.out.println("--- Find the first word starts with 'c' ---");
        Optional<String> startsWithC = Stream.of(lyrics.split("[\\P{L}]+"))
                .filter(s->s.startsWith("c")).findFirst();
        if(startsWithC.isPresent()){
            System.out.println("the first word starts with 'c' = " + startsWithC.get());
        }
    }

}



Tuesday, April 15, 2014

Java Programming Interviews Exposed

Java Programming Interviews Exposed

If you are a skilled Java programmer but are concerned about the Java coding interview process, this real-world guide can help you land your next position

Java is a popular and powerful language that is a virtual requirement for businesses making use of IT in their daily operations. For Java programmers, this reality offers job security and a wealth of employment opportunities. But that perfect Java coding job won't be available if you can't ace the interview. If you are a Java programmer concerned about interviewing, Java Programming Interviews Exposed is a great resource to prepare for your next opportunity. Author Noel Markham is both an experienced Java developer and interviewer, and has loaded his book with real examples from interviews he has conducted.


  • Review over 150 real-world Java interview questions you are likely to encounter
  • Prepare for personality-based interviews as well as highly technical interviews
  • Explore related topics, such as middleware frameworks and server technologies
  • Make use of chapters individually for topic-specific help
  • Use the appendix for tips on Scala and Groovy, two other languages that run on JVMs

  • Veterans of the IT employment space know that interviewing for a Java programming position isn't as simple as sitting down and answering questions. The technical coding portion of the interview can be akin to a difficult puzzle or an interrogation. With Java Programming Interviews Exposed, skilled Java coders can prepare themselves for this daunting process and better arm themselves with the knowledge and interviewing skills necessary to succeed.

    Tuesday, April 8, 2014

    nashorn JavaScript exercise, call Java method from JavaScript

    This example show how to call Java javaStaticMethod() in "javatestnashornjavascript.JavaTestNashornJavascript" class.

    JavaTestNashornJavascript.java
    package javatestnashornjavascript;
    
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.net.URISyntaxException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.script.Invocable;
    import javax.script.ScriptEngine;
    import javax.script.ScriptEngineManager;
    import javax.script.ScriptException;
    
    /**
     * @web http://java-buddy.blogspot.com/
     */
    public class JavaTestNashornJavascript {
        
        final String myJavascript = "<path to myjavascript.js>";
        
        JavaTestNashornJavascript(){
            ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
            ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");
    
            try {
                FileReader fileReader = new FileReader(myJavascript);
                nashorn.eval(fileReader);
    
                Invocable invocable = (Invocable) nashorn;
    
                Object jsResult = invocable.invokeFunction(
                        "javascriptFunction", "Java-Buddy");
                System.out.println("result returned to Java from JavaScript: " + jsResult);
    
            } catch (FileNotFoundException 
                    | ScriptException 
                    | NoSuchMethodException ex) {
                Logger.getLogger(JavaTestNashornJavascript
                        .class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
        public static String javaStaticMethod(String para){
            System.out.println("javaStaticMethod("+para+") called");
            String rev = new StringBuilder(para).reverse().toString();
            return rev;
        };
    
        public static void main(String[] args) throws URISyntaxException {
            
            JavaTestNashornJavascript javaTestNashornJavascript = 
                    new JavaTestNashornJavascript();
    
        }
    
    }
    


    myjavascript.js
    var javascriptFunction = function(para){
        
        print("para passed from Java to JavaScript: " + para);
        
        var myClass = Java.type("javatestnashornjavascript.JavaTestNashornJavascript");
        var revPara = myClass.javaStaticMethod(para);
        
        return "Hello " + revPara;
    };
    



    Monday, April 7, 2014

    nashorn JavaScript exercise, call JavaScript function from Java

    Example to call function and get result in Javascript, from Java code:

    JavaTestNashornJavascript.java
    package javatestnashornjavascript;
    
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.net.URISyntaxException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.script.Invocable;
    import javax.script.ScriptEngine;
    import javax.script.ScriptEngineManager;
    import javax.script.ScriptException;
    
    /**
     * @web http://java-buddy.blogspot.com/
     */
    public class JavaTestNashornJavascript {
        
        final String myJavascript = "<path to myjavascript.js>";
        
        JavaTestNashornJavascript(){
            ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
            ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");
    
            try {
                FileReader fileReader = new FileReader(myJavascript);
                nashorn.eval(fileReader);
    
                Invocable invocable = (Invocable) nashorn;
    
                Object jsResult = invocable.invokeFunction(
                        "javascriptFunction", "Java-Buddy");
                System.out.println("result returned to Java from JavaScript: " + jsResult);
    
            } catch (FileNotFoundException 
                    | ScriptException 
                    | NoSuchMethodException ex) {
                Logger.getLogger(JavaTestNashornJavascript
                        .class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    
        public static void main(String[] args) throws URISyntaxException {
            
            JavaTestNashornJavascript javaTestNashornJavascript = 
                    new JavaTestNashornJavascript();
    
        }
    
    }
    


    myjavascript.js
    var javascriptFunction = function(para){
        print("para passed from Java to JavaScript: " + para);
        return "Hello " + para;
    }
    



    more nashorn JavaScript exercise:


    Hello from java-buddy, with nashorn JavaScript Engine.

    JDK 8 introduces a new Nashorn JavaScript engine written in Java, which is an implementation of the ECMAScript Edition 5.1 Language Specification. Know more by reading Java Platform, Standard Edition Nashorn User's Guide.

    it's a simple example to print hello message using "nashorn" ScriptEngine.



    package javatestnashornjavascript;
    
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.script.ScriptEngine;
    import javax.script.ScriptEngineManager;
    import javax.script.ScriptException;
    
    /**
     * @web http://java-buddy.blogspot.com/
     */
    public class JavaTestNashornJavascript {
    
        public static void main(String[] args) {
            
            ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
            ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");
            
            try {
                nashorn.eval(
                    "print('Hello from java-buddy, with nashorn JavaScript Engine.');");
            } catch (ScriptException ex) {
                Logger.getLogger(JavaTestNashornJavascript.class
                        .getName()).log(Level.SEVERE, null, ex);
            }
            
        }
        
    }
    


    more nashorn JavaScript exercise:


    Friday, April 4, 2014

    Java 8 Lambdas: Pragmatic Functional Programming

    Java 8 Lambdas: Pragmatic Functional Programming

    If you're an experienced Java programmer, Java 8 Lambdas shows you how to make use of your existing skills to adapt your thinking and your codebase to use lambda expressions properly. Starting with basic examples, this book is focused solely on Java 8 language changes and related API changes, so you don’t need to buy and read a 900 page book in order to brush up. Lambdas make a programmer's job easier, and this book will teach you how. Coverage includes introductory syntax for lambda expressions, method references that allow you to reuse existing named methods from your codebase, and the collection library in Java 8.


    Thursday, April 3, 2014

    Advanced Topics in Java: Core Concepts in Data Structures

    Advanced Topics in Java: Core Concepts in Data Structures

    Java is one of the most widely used programming languages today. It was first released by Sun Microsystems in 1995. Over the years, its popularity has grown to the point where it plays an important role in most of our lives. From laptops to data centers, game consoles to scientific supercomputers, cell phones to the Internet, Java is everywhere! There are tons of applications and heaps of websites that will not work unless you have Java installed, and more are created every day. And, of course, Java is used to power what has become the world's most dominant mobile platform, Android.

    Advanced Topics In Java teaches the algorithms and concepts that any budding software developer should know. You'll delve into topics such as sorting, searching, merging, recursion, random numbers and simulation, among others. You will increase the range of problems you can solve when you learn how to create and manipulate versatile and popular data structures such as binary trees and hash tables.

    This book assumes you have a working knowledge of basic programming concepts such as variables, constants, assignment, selection (if..else) and looping (while, for). It also assumes you are comfortable with writing functions and working with arrays.  If you study this book carefully and do the exercises conscientiously, you would become a better and more agile software developer, more prepared to code today's applications - no matter the language.

    What you’ll learn
    •      What are and how to use some advanced algorithms, implemented in Java
    •      How to create, manipulate and use linked lists, stacks and queues
    •      How to use random numbers to program games and simulations
    •      How to work with files, binary trees and hash tables
    •      Sophisticated sorting methods such as heapsort, quicksort and mergesort
    •      How to implement all of the above in Java

    Who this book is for
    This book is for those with a working knowledge of basic software development topic concepts, such as variables, constants, assignment, selection (if..else) and looping (while, for). It also assumes you are comfortable with writing functions and working with arrays.

    Table of Contents
    1. Sorting, Searching and Merging
    2. Introduction to Objects
    3. Linked Lists
    4. Stacks and Queries
    5. Recursion
    6. Random Numbers, Games and Simulation
    7. Working with Files
    8. Introduction to Binary Trees
    9. Advanced Sorting
    10. Hash Tables

    Wednesday, April 2, 2014

    Copy Array

    This exercise show various case in copy array. Imagine a case, I have a array of char, char[]. In each step, only one element of the array will be changed. And I have to record the content of the array in each step. So I create a queue of array of char to save the record. The pseudo code is like this:

    - new a queue of array of char, Queue<char[]> myQueue = new LinkedList<char[]>().
    - new a array of char with default value, myArray = new char[] {' ', ' ', ' '}.
    - change the 1st char in myArray, and add it to myQueue.
    - change the 2nd char in myArray, and add it to myQueue.
    - change the 3rd char in myArray, and add it to myQueue.

    Actually, it is not work! Because in Java, when we pass a array to a method, it pass the reference of the array. That means all the items in the queue point to the same object of array. The result is when we change any char in myArray, all items in myQueue will be changed.

    The solution is to clone() to another array, or even create another array, before passing and add to the queue. The following code and out show the details.

    package javatestarray;
    
    import java.util.LinkedList;
    import java.util.Queue;
    
    /**
     *
     * @web http://java-buddy.blogspot.com/
     */
    public class JavaTestArray {
        
        class MyClass{
            
            Queue<char[]> myQueue;
            
            MyClass(){
                myQueue = new LinkedList<char[]>();
            }
            
            public void insert (char[] arrayIn){
                myQueue.add(arrayIn);
            }
            
            public void printAll(){
                while(!myQueue.isEmpty()){
                    char[] removedItem = myQueue.remove();
                    System.out.print(removedItem);
                    System.out.println(" : " + removedItem.toString());
                }
            }
        }
        
        class MyAnotherClass{
            
            Queue<Character> myQueue;
            
            MyAnotherClass(){
                myQueue = new LinkedList<Character>();
            }
            
            public void insert (char charIn){
                myQueue.add(charIn);
            }
            
            public void printAll(){
                while(!myQueue.isEmpty()){
                    Character removedItem = myQueue.remove();
                    System.out.print(removedItem);
                    System.out.println(" : " + removedItem.toString());
                }
            }
        }
    
        JavaTestArray(){
            MyClass myObj1 = new MyClass();
            char[] myArray1 = new char[] {' ', ' ', ' '};
            myArray1[0] = 'A';
            myObj1.insert(myArray1);
            myArray1[1] = 'B';
            myObj1.insert(myArray1);
            myArray1[2] = 'C';
            myObj1.insert(myArray1);
            myObj1.printAll();
            
            MyAnotherClass myAnotherObj = new MyAnotherClass();
            char myChar = 'A';
            myAnotherObj.insert(myChar);
            myChar = 'B';
            myAnotherObj.insert(myChar);
            myChar = 'C';
            myAnotherObj.insert(myChar);
            myAnotherObj.printAll();
            
            MyClass myObj2 = new MyClass();
            char[] myArray2 = new char[] {' ', ' ', ' '};
            myArray2[0] = 'A';
            myObj2.insert(myArray2.clone());
            myArray2[1] = 'B';
            myObj2.insert(myArray2.clone());
            myArray2[2] = 'C';
            myObj2.insert(myArray2.clone());
            myObj2.printAll();
            
            MyClass myObj3 = new MyClass();
            char[] myArray3 = new char[] {'A', ' ', ' '};
            myObj3.insert(myArray3);
            myArray3 = new char[] {'A', 'B', ' '};
            myObj3.insert(myArray3);
            myArray3 = new char[] {'A', 'B', 'C'};
            myObj3.insert(myArray3);
            myObj3.printAll();
            
            MyClass myObj4 = new MyClass();
            myObj4.insert(new char[] {'A', ' ', ' '});
            myObj4.insert(new char[] {'A', 'B', ' '});
            myObj4.insert(new char[] {'A', 'B', 'C'});
            myObj4.printAll();
        }
       
        public static void main(String[] args) {
            JavaTestArray myJavaTestArray = new JavaTestArray();
        }
        
    }