Sie sind auf Seite 1von 154

[ Home ]

What's New in Java 1.5?


Contents
The Changes
Generics
For/in loop
Autoboxing/Unboxing
Typesafe Enums
Varargs
Static Import
Annotations (Metadata)
How it will affect you NOW
To add to your lesson plan...
How it will affect you eventually...
How can the new features help?
References
Summary:
Sun has recently "upgraded" the Java language to include many new features such as Generics, Type-
Safe Enumerations, Automatic Boxing and Unboxing, Annotations, For/In loops, and Static Imports.
How will this affect the way you teach APCS? Immediately, it will have a minimal effect, but as you
need to expand the scope of your APCS course to encompass the new features it might be difficult to
find time. I'm going to discuss the current effect 1.5 has on APCS as well as possible future
implications it may have on your course.

1. The Changes
I'm going to start by describing the major changes in this new, more robust language. Many of the
effects will become more clear as each new component is described.

The Big List


 Generics
 For/in loop
 Autoboxing/Unboxing
 Typesafe Enums
 Varargs
 Static Import
 Annotations (Metadata)
1.1 Generics
Generics provide a way to create and use typesafe data structures. This means that no longer do you
have to create a List of the basic Objects then typecast every time you pull stuff out! You can declare
your list to automatically typecast the stuff inside:

List things = createListOfBorkObjects();


for(Iterator i = things.iterator() ; i.hasNext() ; ) {
Bork item = (Bork)i.next();
//do something useful
}
Simply becomes...

List<Bork> things = createListOfBorkObjects();


for(Iterator<String> i = things.iterator() ; i.hasNext() ; ) {
Bork item = i.next();
//do something useful
}
The Java compiler also protects things from having non-Bork objects inside. If you try to put a String
or anything else in, you'll get an error. This essentially means that you can create a list with specific
types now instead of just objects. These exist in other classes such as Map which uses two:

Map<String, Bork> myMap = new HashMap<String, Bork>();


That creates a map that uses a String key and a Bork value. This implementation kind of looks like
something using templates in C++...

Be careful though! You can create a string iterator that iterates over a list of non-strings that will only
become an error at runtime. The compiler doesn't catch this.

Also, sometimes when using a type that can be parameterized, but not specifying the parameter type (in
angle brackets) you can get lint warnings. This just means that you haven't provided a specific type,
and the current definition of the type is "fuzzy" -- like lint, get it?

1.2 For/in loop


This is probably one of the coolest new features. I personally hate using iterators--it seems redundant
and annoying sometimes. Well, lucky for me there's a way around them now!

So now you can do this:

for(Iterator lineup = list.iterator() ; lineup.hasNext() ; ) {


Object thatThing = lineup.next();
myMonster.eat(thatThing);
}
In a shortened:

for(Object thatThing : list) {


myMonster.eat(thatThing);
}
Much prettier, no? This works with arrays too.

int[] nums = { 1, 2, 3, 4, 5, 6 };

for(int n : nums) {
System.out.println(n);
}
Say you want to get your class to work with this nifty loop. Then, you have to implement Iterable (or
extend something that does). This involves telling Iterable what type of things you iterate over. You can
define a custom iterator to do something more robust, but for this illustration, I'm just going to grab one
out of the list.
public class MailBox implements Iterable<MailMessage> {
/** structure storing the messages */
private ArrayList<MailMessage> messages;

//...

/**
* Implemented for Iterable.
*/
public Iterator<MailMessage>() {
return messages.iterator();
}

//...
}
For more detailed information, see Java 1.5 Tiger: A Developer's Notebook[4] or the information on
Sun's J2SE 5.0 language documentation.

1.3 Autoboxing/Unboxing
Integer i = new Integer(4);
int j = i.intValue();
Number n = new Float(3.14159);

Boolean stuff = new Boolean(false);


// stuff before ? must be a boolean (lower case)
System.out.println( stuff.booleanValue() ? "Yep" : "Nope" );
Sick of this? Me too. Do this instead:

Integer i = 4;
int j = i;
Number n = 3.14159f;

Boolean stuff = false;


System.out.println( stuff ? "Yep" : "Nope" );
This is pretty nice. Especially since you can use ++ and other similar operators with the wrapper types
now too.

1.4 Typesafe Enums


Enums are just magic classes to help prevent the methodless-interface antipattern. They let you make
classes that will enumerate values, but also keep the types specific. Before, we could simulate enums
with a bunch of static final int variables or something. The problem with those is that you could
confuse any int with one of the constants. With enumerations, only the values in the enum are valid.
For example:

public enum JettStaff {


ADRIAN,
ARIJIT,
BETH,
ERIC,
KATIE,
KATY,
RAJA,
RICH,
SUZANNE
};

JettStaff x = JettStaff.SUZANNE;
Now, it gets even cooler. I don't have to keep track of separate information to store, say the peoples' full
names. I can associate them directly, just like in a class! Each of the values of JettStaff are instances of
the JettStaff enumeration, so we can define a constructor and a toString() method.

public enum JettStaff {


ADRIAN("Adrian German"),
ARIJIT("Arijit Sengupta"),
BETH("Beth Plale"),
ERIC("Eric Wernert"),
KATIE("Katie A. Siek"),
KATY("Katy Borner"),
RAJA("Raja Sooriamurthi"),
RICH("Rich Kick"),
SUZANNE("Suzanne Menzel");

private String name;

public JettStaff(String n) { this.name = n; }


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

JettStaff x = JettStaff.SUZANNE;
System.out.println(x);
But wait, it gets cooler! Now you can also give each enumerated value a custom body. Since they're
each instances, you could design a toString() method for each:

public enum JettStaff {


ADRIAN("Adrian German") {
public String toString() {
return name + " (dgerman@indiana.edu)";
}
},
ARJIT("Arjit Sengupta") {
public String toString() {
return name + " (asengupt@indiana.edu)";
}
},

// and on for the rest...

private String name;


public JettStaff(String n) { this.name = n; }
}

JettStaff x = JettStaff.SUZANNE;
System.out.println(x);
Last but not least, enums can extend each other. Imagine that!

1.5 Varargs
What is your impression of "..."? It's a nice little note that might come in handy. Notice how when you
pass arguments from the command line ...

C:/> java MyProg a b c


You gave me 3 args! Yay.
...
... you don't have to pass an array of stuff. The runtime automatically converts the arguments into an
array of strings. You can do that now in all of your methods! For example, instead of doing this:

public class VarArgs {


public static void main(String[] args) {
String[] newArgs = {"a", "b", "c"};
vaMethod(newArgs);
}

public void vaMethod(String[] args) {


System.out.println("You gave me " + args.length + " args! Yay.");
}
}
You can declare it more easily, and not have to construct the array ahead of time:

public class VarArgs {


public static void main(String[] args) {
vaMethod("a", "b", "c");
}

public void vaMethod(String... args) {


System.out.println("You gave me " + args.length + " args! Yay.");
}
}
Notice that when you use the ... syntax, it automatically treats that parameter as an array but you don't
have to pass it in that way. Nifty. Let's add one of those for/in loops:

public class VarArgs {


public static void main(String[] args) {
vaMethod("a", "b", "c");
}

public void vaMethod(String... args) {


for(String s : args)
System.out.println(s);
}
}
1.6 Static Import
Remember making all those interfaces that just have constants in them?

import java.awt.*;

public interface BouncingBallConstants {


public static final Color BACK_COLOR = Color.WHITE;
public static final Color BALL_COLOR = Color.BLUE;
public static final int BALL_SIZE = 50;
}
Scrap that. Put these into a REAL class and then just import the static members from all the other ones
using import static <Package or Class>;. This addition is pretty straightforward, and it helps prevent
bloat and the "methodless interface" design antipattern.

1.7 Annotations (Metadata)


Now for the weirdest part. Annotations are not really something that will affect how you program in
Java, unless you need to associate some sort of metadata or annotations with classes, methods,
variables, etc.

So what are annotations anyway? That's a good question. They provide a little extra information about
the classes you write, and a class can use the Reflection package later to read the annotations. These are
useful because you can attach extra information to your code that may determine how it is used or
maybe if it is used at all.

For example, in J2SE 5, you can declare your intent to override a method like toString() in one of your
classes:

public class MyClass extends Object {


@Override
public String toString() {
return "My overridden method!";
}
}
In the above example, we declare that we will override the immediately following toString() method.
So the compiler looks in our superclass (Object) for the same metho and makes sure it exists. If for
some reason we had overloaded toString() by declaring it with different parameters and maybe return
type, then the compiler would throw an error saying we didn't override correctly. This is really useful if
you want to make sure you override a method as opposed to simply overloading it.

Of course you can define your own annotations. They're basically like interfaces, but they can contain
values. An example annotation looks like:

public @interface Conference {


String what();
String when();
String location();
}
This annotation declares three members: what, when, location and sets them up to have "getters" and
"setters" automatically! That means each @Conference annotation has those three fields associated
with it, and I don't have to define the accessor and mutator methods to set them up (see the next code
listing). If I define this annotation like this, I can use it to mark code that I use for the Jett conference:

@Conference(what="JETT",
when="November 2004",
location="IUB")
public class MyMagicJettClass {
//...
}
And now the @Conference type of data is associated with my class. Later on, I could write an analyzer
that goes through all of my code and lets me know which classes were used at conferences as well as
which conferences they were used at and when. This specific example doesn't have any effect on the
way MyMagicJettClass operates.

So the annotations require two-fold cooperation: the programmer must properly annotate her code to
provide adequate metadata needed and other developers who will want to know this metadata must
know how to extract it using the Java Reflection package. That's a whole hours-long session on how to
extract them, so I'm not going to go into depth here.

Where are they useful? Say you are working with RMI (Remote Method Invocation) and you don't
want all of your methods available remotely. You could annotate the remotable ones with a @Remote
annotation, then whatever serves up the remote access can only allow those to be remotely accessed.
There are a ton of great uses for these, and they are fully extendable (you can annotate annotations)!

2. How it will affect you NOW


All of the previous Java language features will still work. Some are deprecated, but not very many. You
should also know that the 2004 exam was written before 1.5 was available, so its features are not at all
critical.

The topics covered by the exam don't include generic typing, annotations/metadata or variable
arguments (since really they're just language features and not so much programming constructs). This is
good news, since if your students don't immediately master these new features it won't harm them.

What if my students use new 1.5 language features on the exam? If they're used properly (and the code
is well-designed), the readers will most likely not deduct any points. But in the end the deductions are
up to the readers. Automatic boxing and unboxing as well as correct use of the for/in loop will be
acceptable.

The biggest problem would be a student who tries to use one of these new features (such as generics or
enums) but misuses them terribly, obscuring the code. Then a reader might not at all understand what
constructs the student was trying to use and mistake it for non-code garbage. Because the readers are as
new to the 1.5 features as we are, we cannot expect them to have mastered everything to the point of
being able to identify misuse of one.

2.1. To add to your lesson plan...


You may not want to add much of this to your lesson plan immediately, since most of it is not necessary
for good programming. Sneaking in the for/in loop and autoboxing and unboxing would be quite
simple (since the students are likely to leave out the manual boxing and unboxing regardless if the
compiler doesn't complain). At least for the time being, if the students can understand Java and write
good 1.4 code, it will most likely be acceptable.

3. How it will affect you eventually...


Nobody knows. Really it's up to the AP board and college CS departments where we go from here.
How much of this new Java stuff becomes mainstream and intravenous so that we breathe it like
objects? It is my personal opinion that the generics, for/in loop, autoboxing static import and varargs
stuff is all syntax sugar: it's just a little bit of convienience and not a really big construct such as other
big paradigm shifts like procedural to object oriented programming.

3.1. How can the new features help?


So now I step off my soapbox and ask you to think of how these new features might streamline your
teaching methods. How can you work these into your lesson plan to help teach the ideas of
polymorphism, generic types, AOP (Aspect oriented programming: the annotations stuff), and
enumerations? In what ways can they help you teach the current topics in a more streamlined way?

References
J2SE(tm) 5.0 New Features. Sun Microsystems.
http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html
New Language Features for Ease of Development in the Java 2 Platform, Standard Edition 1.5: A
Conversation with Joshua Bloch. Heiss, Janice J. May 8, 2003. Sun Microsystems.
http://java.sun.com/features/2003/05/bloch_qa.html
Java 1.5: Where does it fit into AP Computer Science?. Weiss, Mark. Florida International University.
AP Central & Collegeboard.com. http://apcentral.collegeboard.com/members/article/1,3046,151-165-0-
36930,00.html
Java 1.5 Tiger: A Developer's Notebook. McLaughlin, Brett & Flanagan, David. O'Reilly Media, Inc,
2004 ISBN 0-596-00738-8.
What are New Features in JAVA SE 6
Linked List Example In Java
Java set example
TreeSet
Java faqs
Java Web Start and Java Plug-in
Set Interface
Custom Collection Implementations
Introduction to Collection Algorithms
Introduction to collection Implementations
Introduction to Map and SortedMap Interface
Java SE 6
Introduction to List and Queue Interface
Java SE 6
Collection Interfaces
Introduction to Collections Framework
Enhancements in Networking Features
Java Web Start Enhancements in version 6
Changes in Jar and Zip
New Features of JAVA SE 6.
Changes in I/O
Introduction to Collections API
Advantages and Disadvantages of the Collection Framework
Java 6.0 Collection Framework
Collections Framework Enhancements
Navigable Map Example
Navigable Set Example
HashSet Example
Linked List Example
Tree Map Example
Tree Set Example

Here are the new features of the version 6 of the Java Standard Edition (SE).

Web services: Developers have to get first class support for writing XML web services. The latest Java
SE 6 provides new adds parsing and XML to Java object-mapping APIs. as .net interoperable web
services with a simple annotation.
Collections Framework Enhancement: With the new Java SE features, now it is easy in Collection
framework and we are able to improve the performance hashing function that is used by
java.util.HashMap. It provides some new Collection interfaces also.
Monitoring and Management: The major benefit for the new Java SE is that it provides you facility,
which adds yet more diagnostic information and memory heap analysis tool jhat for forensic
exploration of those core dumps.
Changes in jar and zip: The major changes for Java SE 6 has been done in terms of Jar and zip support
as it has been enhanced. In this, two new compressed streams have been added. These are java.util.zip.
DeflaterInputStream and java.util.zip.InflaterOutputStream.
Java Platform Debugger Architecture Enhancements: JVMDI has been deleted in JAVA SE 6 and JPDA
has been added. Some new Methods are included like boolean boolean canGetInstanceInfo() and much
more?
Security:The Java SE 6 has simplified the work for its security administrators by providing various
means of anger. The Java SE 6 provides a large set of security APIs. These Security APIs span a wide
range of areas, including cryptography public key infrastructure, secure communication, authentication,
and access control.
Enhancement in RMI for JDKTM 6:java.rmi.MarshalledObject now support generics
JMX API Enhancements: Enhancements has been made to the JMX API in Java SE 6 like : JMX API
now completely supports Generics, MXBeans have been added and much more?
Networking features and enhancements in Java SE version 6.0:
This feature include enhancement in networkInterface, support for Internationalized Domain Names,
HTTP Negotiate Authentication and much more?

Serialization Changes and Enhancements in JAVA SE Development Kit 6


The new method ObjectStreamClass.lookupAny now used to obtain an ObjectStreamClass instance for
a non-serializable Class

JAX-Web Services 2.0 with the Java SE 6 Platform: One of the most exciting new features of the JAVA
SE 6 is support for the Java API for XML Web Services (JAX-WS), version 2.0.

Linked List Example In Java


LikedList implements List interface which perform all operation  like add, remove, delete etc. LinkedList class provide  method to insert,
remove , to get the element, insert at the beginning. These operation allow linkedList to use as stack, queue, dequeue. This class can implement
dequeue interface which provide first in first out, for add, remove along with other stack operation. The operation which perform adding or
removing element will traverse the element from beginning and end of the list.

LinkedList has following constructor:

LinkedList() : Create a empty linked list.


LinkedList(Collection c) : Create a linked list which initialize the element from collection.
LinkedList class define some useful method which manipulate and access the element.

Some of the element of linked list are as follows:

void addFirst(Object ob) : Add element to the beginning of the list.


void addLast(Object ob) : Add element at the last of the list.
Object getFirst() : To get the first element.
Object getLast() : To get the last element.
Object removeFirst():  To remove the first element from the List.
Object removeLast() : To remove the last element from the List.
The following program will illustrate the LinkedList example

import java.util.*;

public class LinkedListDemo {

public static void main(String args[])

LinkedList list = new LinkedList();


// add elements to the linked list

list.add("W");

list.add("B");

list.add("K");

list.add("H");

list.add("L");

list.addLast("Z");

list.addFirst("A");

list.add(1, "A2");

System.out.println("Original contents of list: " + list);

// remove elements from the linked list

list.remove("B");

list.remove(3);

System.out.println("Contents of list after deletion: "+ list);

// remove first and last elements

list.removeFirst();

list.removeLast();

System.out.println("list after deleting first and last: "+ list);

// get and set a value

System.out.println("list after change: " + list);

Output from the program:

Java set example


In this section you will learn about set interface in java. In java set is a collection that cannot contain duplicate element. The set interface contains
method that inherited from collection which does not allow you to add duplicate elements in the set. The set interface has method which are as
follows :

add() : Which allow to add an object to the collection..


clear() : Remove all object from the collection.
size() : Return the size of element of collection.
isEmpty() : Return true if the collection has element.
iterator() : Return an iterator object which is used to retrieve element from collection.
contains() : Returns true if the element is from specified collection.
Example of java set interface.

import java.util.Iterator;

import java.util.Set;

import java.util.TreeSet;

public class SetInterface {

public static void main(String args[])

Set s=new TreeSet();

s.add(10);

s.add(30);

s.add(98);

s.add(80);

s.add(10); //duplicate value

s.add(99);

Iterator it=s.iterator();

while(it.hasNext())

System.out.println(it.next());

System.out.println("Size of Set is = "+s.size());

System.out.println("set is empty = "+s.isEmpty());

Description : In the above code creating a set interface reference and adding element to the collection. As we know set does not allow duplicate
elements,  so after adding 10 again we have added 10 to the collection but it wont displayed the value 10 two times. and when we compile and
execute the it will display the element in ascending order.

Output : After compiling and executing the program


TreeSet
We will discus about treeSet() method. The treeSet implement the Set interface. we have stored collection of data and data order of element. We
have stored date string and Integer value. Set interface are many abele method size(), add(), addAll(),iterator(), remove(Object o), clear(), clone(),
comparator(),Object toElement), tailSet(Object fromElement).

TreeSet method are:-

Size().
add().
iterator().
remove().
Size().Method:-We get a size of collection of data used for size() method and we contain 4 elements size of the treeSet, which can be determined
by calling size() method.

add().Method:-We have added the element used for add() method. If same element already exists it will not be stored.

iterator(). Method:-This method returns an iterator elements of the set interface.

remove().Method:- Remove method removes given elements in set interface.

package Collection;

import java.util.Iterator;

import java.util.TreeSet;

public class TreeSetExample {

public static void main(String[] args) {

TreeSet example = new TreeSet();

example.add("C");

example.add("A");

example.add("D");

example.add("B");

example.add("E");

example.add("G");

example.add("F");

example.add("I");

example.add("J");

example.remove("I");
Iterator iterator;

iterator = example.iterator();

System.out.println("Tree set string character arrangements are: ");

while (iterator.hasNext()) {

System.out.println(iterator.next() + " ");

System.out.println("Tree Set size: " + example.size());

OutPut:-

Java faqs
This section contains collection of frequently asked questions(faqs) in interview or viva of Java.

Q. What is the difference between Interface and abstract class ?

Ans:

Abstract Class Interface


An abstract class can have
All of the method in an interface is
implementation of some of its
abstract. You don't need to
method with some abstract method.
put abstract keyword in front of
Abstract method declares
every method.
with abstract keyword.
The field declare in Abstract class
The  field declared in Interface must
can have any type private, public
be static and final.
extra.
It can have constructors. It can't have constructors.
A class can't extends interface,  An interface can extend another
it implements  interface. interface
A class can extend only one A class can implements several
abstract class. interface.
The subclass of an abstract class
must implements all of the abstract A class implementing an interface
methods in the super class. But has to implements all the methods
need to implement no abstract of the interface.
methods.
Q. What is synchronization in multithreading ?

Ans: In multithreading, synchronization is the mechanism to control the access of multiple threads to shared resources. Without access control
using synchronization, it is possible that one thread modify the resource which is used by another thread , at the same time, for modification. This
could lead to serious error.
Q. What is static in Java ?

Ans: Static means one per class regardless of how many instances it have. This means you can use static elements without instantiating the class.
You can use Static method of a super class into a static method of its subclass unless method is not declared final. It means you can't use a static
method within a nonstatic method.

Q. What is final ?

Ans : If a class is final, it can't be extended means it can' t be sub classed. If a method is final, it can' t be override. If a variable is final, you can't
alter it.

Q. What are the different states of thread ?

Ans : Following are the different states of thread :

Instantiated
Runnable
Running
Wait/blocked/Sleep
Completed
Q. Difference between HashMap and Map ?

Ans : Map is the Interface and HashMap is the class that implements it.

Q. Difference between Vector and ArrayList?

Ans : ArrayList is not synchronized while Vector is synchronized.

Q. What are different types of inner classes?

Ans. Following are the type of inner classes :

Nested top-level classes


Member classes
Local classes
Anonymous classes

Java Web Start Enhancements in version 6


       
JNLP Specification addition of the <update> element - The <update> element with its attributes "policy" and "check" is now
supported. It describes the applications preferences for how Java Web Start should check for updates on the web, and what to do when
it is known before starting the application that there is an update available.
Prior to Java SE 6, In Java Web Start <offline-allowed> element was overloaded for two things. First, the application can run in offline
mode. Second, Try to check for updates before running an application (when not run in offline mode) could time out. When a times out,
the application would launched to the cache wile and the updates check continued in the background.

In Java SE 6, the "policy" attribute of <update> element is used to determine what to do when when it is known before launching the
application that an update is available. The values of policy attribute can be "always" (default value), "prompt-update" or "prompt-run".
Because of "check" attribute of <update> element in version 6, the <offline-allowed> element has no more its second meaning that
discussed above. Default values : <update check="timeout"/> has same behavior was specified by <offline-allowed> in previous
version. Whenever <offline-allowed> was previously used, for that behavior you need to specify <update check="always"/>. A <update
check="background"/> can be specified to always immediately launch from the cache while spawning a check for update in the
background.
JNLP Specification relaxation is required for the DownloadService API - Upto now we used to pass the URLs as arguments to all
APIs were restricted to be used a URLs to resources listed in the jnlp files. In this version there is not any such restrictions for signed
and trusted code there is no restriction on untrusted code that it has to be listed in the jnlp files but the only requirement is that it should
be from the same codebase. 

But in current version, URLs to jnlp files are allowed, so that by using DownloadService.removeResource() you can remove a whole
application from cache and by using DownloadService.load Resource() you can import an application. Due to this change now
resources is not listed in jnlp file can now be used in an application.
SocketService Implementation - A clarification in the definition of the sandbox is also a another important specification change, that
is only the default sandbox, this implementation is free to prompt the user to allow actions that are not allowed by the sandbox. In Java
1.5, it was done for printing, so that in AWT by using printing API, you can expand the sandbox for allowing the application to access
the printer. But in Java SE 6, it is done for socket connection, that's why if an untrusted application try to connect to a url, the user can
be prompted to allow the connection.
Replace <j2se> element by new <java> element in JNLP file - This element will be used only with Java Web Start version 6 for jnlp
files. The <j2se> element is replaced by <java>tag (The main reason of behind that is only the Java Platform Standard Edition is no
longer known as j2se).
Enhanced <association> element now contain the <icon> and <description> sub-elements - When creating file extension and
mime type associations with Java Web Start application, you can specify description and a separate icon to be used for each association.
JNLP is now an instance of the URLClassLoader - It gives some powerful advantages. First, Jar indexing is now fully supported. If
you want to create a jar index of several jar file in the main jar file that indexes all the jar files, and then you can mark each additional
jar as lazy, and it can be download only when a resource or class in it is referenced. Second, The JNLPClassLoader was rewritten to
extend URLClassLoader. For getting a list of jar elements that are listed in the jnlp files an application can invoke getURLs(). The URL
returned for calls to Class Loader.getResource() is proper Jar URL of the item on the net. By extending URLClassLoader, it allows Java
Web Start to operate without caching.
Java Web Start now supports icon formats - Now, two icon formats "png", "ico" are supported by Java Web Start. This
enhancement allows to specify an icon that would not be translated into a different format depending on its use. Now you can specify a
icon format kind="shortcut" with width and height attributes. Example - <icon kind="shortcut" href="desktopshortcut.ico" width="32"
height="32"/> <icon kind="shortcut" href="menushortcut.ico" width="16" height="16"/>. For destktop shortcuts use the icon size is
closer to 32 x32 and for menu shortcut its closer to 16 x 16.
Add/Remove entries will now supported on Windows for Java Web Start - Add/Remove entries will now include will now include
the publisher, install date, publisher websight and application icon from the jnlp file information block.
Desktop shortcut tooltips - Java Web Start creates a Desktop shortcuts. In Jnlp file Java Web Start will use the <description> element
to create a tooltip for describing the application.
Enhanced JNLPDownloadServlet - Now, the enhanced JNLPDownloadServlet contains the two macro $$hostname and a $$sight.
The expanded $$hostname contains the host name and $$sight contains the web site address without the WAR context portion.
The safe vm args and properties list has been enhanced and some Command Line Interface (CLI) items are also changed or added.

Java Web Start and Java Plug-in Common Enhancements


Cache and System Format

In Java SE 6, the cache format has been fully changed. That's why, any existing code using previous format of cache for Java Web Start or Java
Plug-in will no longer work. Existing applications cache will be upgraded and converted to the new format of cache when the first time you
launch a Java Web Start application, or by launching the cache viewer using javaws-viewer. And System cache will upgraded when the first time
you run Java Web Start application in system mode, or just launching javaws - system.

Download Engine and Cache Consolidation

Download Engine and entire caching mechanism are redesigned and consolidated between Java Web Start and Java Plug-in. This include some
new features in Java Web Start:

By using Java Control Panel it allow to disable the caching.


The maximum cache size set in Java Control Panel is supported in Java Web Start.
A cleanup thread can be started by Java Web Start to removed Least Recently Used (LRU) items from the cache when approaching the
maximum size.
The <no-cache> directive is now supported. When using this directive, and update check is made to verify the cached contents is same
as at the URL.
The expiration-date is supported. If any download resource contains an expiration date, it will not be used after that date.
Secure Versioning

In Java SE 6, signed Java Web Start applications are not affected but the unsigned Java Web Start applications specify a version trigger a security
warning, requiring explicit user permission before running the application.

Other Enhancements

All dialogs and screens have been redesigned by user experience team to be more user friendly and accessible.
Now, Java Console is not included in modality. In Java 6, some new features are added in modality by AWT. By this you can interact
with Java Console even when the application is displaying a modal dialog.
CRL (Certificate Revocation Lists) and OCSP (Online Certificate Status Protocol) are supported by Java Web Start and Java Plug-in
for verifying the certificates.
SSL/TSL are supported by Java Web Start and Java Plug-in. An option has been provided by Java Control Panel to select the default
SSL handshaking protocol. The default is set to SSLv3 and SSLv2, but then user can change it to TSL.

Set Interface
       
The Set interface extends the Collection interface. It neither contains duplicate elements nor  maps a key value to an object. It permits a single
element to be null. The Set interface contains only methods inherited from Collectioninterface, these are shown in the table given below:

Method Uses
 add( ) Adds an object to the collection
 clear( ) Removes all objects from the collection
Returns true if a specified object is an
 contains( )
element within the collection
 isEmpty( ) Returns true if the collection has no elements
Returns an Iterator object for the collection
 iterator( )
which may be used to retrieve an object
Removes a specified object from the
 remove( )
collection
Returns the number of elements in the
 size( )
collection
In the Java platform, Collections Framework provides three general-purpose Set implementation-classes: 

 HashSet
 TreeSet
 LinkedHashSet

HashSet:
This is a class which stores its elements in a hash table and doesn't allow to store duplicate collections. This class permits the null element and is
used to perform the basic operations such as add, remove, contains and size. This is the best way to perform set implementation.

TreeSet:
The TreeSet implementation is useful when you need to extract elements from a collection in a sorted manner. The elements added to a TreeSet
are sortable in an order. It is generally faster to add elements to a HashSet, then converting the collection to a TreeSet for sorted traversal.

 LinkedHashSet:
It is a class which is implements both the Hash table and linked list implementation of the Set interface. This implementation differs
from HashSet that it maintains a doubly-linked list. The orders of its elements are based on the order in which they were inserted into the set
(insertion-order). 

SortedSet Interface:

The SortedSet interface extends the Set interface. It maintains its elements in ascending order.  It neither contains duplicate elements nor  maps a
key value to an object. It permits a single element to be null. In addition to methods of  the Set interface, it also provides two following methods:

 first( )
 last( ) 

The first( ) method returns the first (lowest) element currently in the collection while the last( ) method returns the last (highest) element
currently in the collection.

Let see an example that stores a group of numbers to the Hash table using HashSet class.
import java.util.*;
public class SetDemo {
  public static void main(String args[]) { 
  int count[]={34, 22,10,60,30,22};
 Set<Integer> set = new HashSet<Integer>();
  try{
  for(int i=0; i<5; i++){
  set.add(count[i]);
  }
  System.out.println(set);
  
  TreeSet sortedSet=new TreeSet<Integer>(set);
  System.out.println("The sorted list is:");
  System.out.println(sortedSet);

  System.out.println("The First element of the set is: "+


  (Integer)sortedSet.first());
  System.out.println("The last element of the set is: "+
  (Integer)sortedSet.last());
  }
  catch(Exception e){}
  }
}

Output of the Program:

C:\nisha>javac
SetDemo.java

C:\nisha>java SetDemo
[34, 22, 10, 30, 60]
The sorted list is:
[10, 22, 30, 34, 60]
The First element of the
set is: 10
The last element of the
set is: 60

C:\nisha>
This program creates a HashSet and adds a group of numbers, including a number "22" twice. The program than prints out the list of numbers in
the set, note that the duplicate number is not added to the set. Then the program treats the set as a TreeSet and displays the sorted list of the set.
The first( ) and the last( ) methods display the first & last elements of the set respectively.

Custom Collection Implementations


       
So far you have learnt about the Java  built-in Collection Interfaces implementations. Apart from these, some times programmer need to
implement their own collections classes.  The Java platform allows you to write your own implementation of a core collection interface. It is easy
to write your own  implementation with the help of abstract implementations. 

Lets discuss, why we should make a custom implementation.

Persistent: All of the built-in Collection implementations reside in main memory and appears when the program exits. If you want a
collection to be available for the next time when the program starts, you can implement a collection that is concurrently accessible by
multiple programs.
High-performance, special-purpose: Many data structures take advantage of restricted usage to offer better performance that is
possible with general-purpose implementations. For instance, consider a List containing long runs of identical element values. The runs
can be represented as a single object containing the repeated element. This example is interesting because it deals with two aspects of
performance: It requires less space but more time than an ArrayList.
High-performance, general-purpose: The Java Collections Framework's designers have tried to provide the best general-purpose
implementations for each interface, but many, new ones are invented every day for the High performance of an application.
Convenience: Some times you want additional implementations that offers conveniences than those offered by the Java platform. For
instance, you may need a List to represent a contiguous range of Integers.
To write your own custom implementation is not difficult. Java supports the abstract implementations to implement your own collection. Lets
see the way of writing the custom collection implementation.

import java.util.*;

  class MyClass {

    public static List myList(Object[] a) {

       return new ArrayList(a);

    }

  }

    class ArrayList extends AbstractList

               implements java.io.Serializable {

    

  private Object[] x;

  ArrayList(Object[] array) {

      x = array;

  }

  public Object get(int index) {

      return x[index];

  }

  public Object set(int index, Object element) {

      Object oldVal = x[index];

      x[index] = element;

      return oldVal;

  }

  public int size() {

      return x.length;

  }

    }

  public class CustomImpl{

   public static void main(String[] args) {
        try{

      String s[]={"My", "Custom", "Implementation"};

      Object o;

      int i=0;

      MyClass a= new MyClass();

      List lst=a.myList(s);

      System.out.println("The list is: "+lst);

      ArrayList al=new ArrayList(s);

      o=al.get(1);

      System.out.println("The retrieved element is: "+o);

      String s1="Collection";

      o=al.set(2,s1);

      System.out.println("The set element in place of Implementation is: "+s1);

      System.out.println("Now the new list is: "+lst);

      i=al.size();

      System.out.println("The size of the array list is: "+i);

      }

      catch(Exception e){}

    }

    }

Output of the Program:

C:\nisha>javac
CustomImpl.java

C:\nisha>java CustomImpl
The list is: [My, Custom,
Implementation]
The retrieved element is:
Custom
The set element in place of
Implementation is:
Collection
Now the new list is: [My,
Custom, Collection]
The size of the array list is:
3

C:\nisha>
Description of the Program:

In the given program, a custom implementation of Arrays.myList is defined which calls the constructor of ArrayListclass and pass the object to
it. The get( ) and the set( ) methods of the ArrayList class retrieve and set an element to the specified position of the List.

Introduction to Collection Algorithms


       
Algorithms:

The Collections and Arrays classes, available as a part of the Collections Framework, support various algorithms. The  Java platform provides
great majority of the algorithms to perform different kind of operations such as sortingand searching.

I. Sorting Algorithm:

The sort algorithm reorders a List such that its elements are in ascending order according to an ordering relationship. The sort operation uses a
slightly optimized merge sort algorithm which is fast and stable. TreeSet and TreeMap classes offers a sorted version of sets and maps, there is no
sorted List collection implementation. Sorting of a List is done with the sort( ) method.

For example, the following program prints the arguments (the arguments, given through command line) of a  List in an alphabetical order.
import java.util.*;

public class SortDemo {
  public static void main(String[] args) {
  List<String> list = Arrays.asList(args);
  Collections.sort(list);
  System.out.println(list);
  }
}
 Output of this program:
C:\nisha>java SortDemo this is a
commandline argument
[a, argument, commandline, is, this]

C:\nisha>
Download this program:
Searching Algorithm :

Besides sorting, the Collections and Arrays classes provide a mechanism to search a List or an array, as well as to find the first and last values
within a Collection. The binarySearch algorithm searches for a specified element in a sorted List. This algorithm  takes a List and an element to
search for the search key. This form assumes that the List is sorted in ascending order according to the natural ordering of its elements.

Before searching an element, the List must be sorted, Once you have sorted the List, using Collection.sort( )method, you can perform a quickly
binary search  operation using the overridden binarySearch( ) method. 

For example, the following program prints the sorted arguments list (the arguments, given through command line) and then search the position of
a specified key value.
import java.util.*;

public class SearchDemo {
  public static void main(String[] args) {
  try{
  List<String> list = Arrays.asList(args);
  Collections.sort(list);
  System.out.println("The sorted list is: "+list);
  int pos = Collections.binarySearch(list, list.get(2));
  System.out.println("The position of the searched element is : "+pos 
   +" and the element is:"+list.get(2));
  }
  catch(Exception e){}
 
  }
}
 Output of this program:
C:\nisha>java SearchDemo this is a
commandline argument
The sorted list is: [a, argument,
commandline, is, this]
The position of the searched element is :
2 and the element is:commandline

C:\nisha>

Introduction to collection Implementations


       
The Collections Framework provides a well-designed set of interfaces and classes used for storing and manipulating groups of data into a single
unit. The collections framework is a unified architecture which is used to represent and manipulate collections. The framework allows the
collections to get manipulated independently as well as reduces programming effort for increasing performance. 
It includes implementations of interfaces, and algorithms included in it to manipulate them. Basically it is a unified architecture that consists the
following collections:  

Implementations are the reusable data objects used to store collections, which implement the collection interfaces.  Implementations are also
responsible for documenting the operations which they support. All of the general-purpose implementations of the Java platform support all of the
optional operations.

The following kinds of implementations are described below:

General-purpose implementations: These are the most commonly used implementations, designed for performing all optional
operations contained within the defined interfaces. They are summarized in the table below.
Interfaces Implementations
Hash table
  Hash table Tree Linked list + Linked
list
Set HashSet TreeSet   LinkedHashSet
List     LinkedList  
Queue        
Map HashMap TreeMap   LinkedHashMap

 
The Java Collections Framework provides several general-purpose implementations of the Set, List , and Map interfaces. Each of the
general-purpose implementations provides all optional operations contained in its interface. All permit null elements, keys, and values.

Special-purpose implementations: These are designed to use in special situations and display nonstandard performance
characteristics, usage restrictions, or behavior.
Concurrent implementations: These are designed to support high concurrency. These implementations are part of
the java.util.concurrent package.
Wrapper implementations: These are used in combination with other types of implementations.
Convenience implementations: These are mini-implementations, typically made via static factory methods, that provide convenient,
efficient alternatives to general-purpose implementations for special collections.
Abstract implementations: These are implementations that facilitate the construction of custom implementations.
The following description describes the categories in which the Collection Framework interfaces are implemented.
The Set implementations are grouped into general-purpose and special-purpose implementations. Listimplementations are grouped into general-
purpose and special-purpose implementations. Map implementations are grouped into general-purpose, special-purpose, and concurrent
implementations. The Queue implementations are grouped into general-purpose and concurrent implementations.

Introduction to Map and SortedMap Interface


       
Map Interface:

A Map is an object that maps keys to values. It is not an extension of the collection interface rather it has own interface hierarchy. Map
provides a more general way for storing elements without containing duplicate keys. It allows you to store pairs of elements, termed "keys" and
"values", where each key maps to one value. Thus the keys in a map must be unique.

The Map interface methods can be broken down into three sets of operations:

Altering: The alteration operations allow you to add and remove key-value pairs from the map. Both the key and value can be null.
Querying: The query operations allow the user to retrieve key/value pairs from the Map.
Providing alternative views: This method allow you to work with the different views which can be used to analyze Map key/value Objects.

Map Methods Returning Views:

These methods return objects which allow you to traverse the elements of the Map, and also delete elements from the Map.
Method Uses
Returns a Set view of the mappings contained
in the map. Each element in the set is a
 entrySet() Map.Entry object which can have it's key and
value elements accessed with getKey() and
getValue() methods (also has a setValue()
method)
Returns a Set view of the keys contained in the
map. Removing elements from the Set will also
keySet()
remove the corresponding mapping (key and
value) from the Map
Returns a Collection view of the values
contained in the map. Removing elements from
values() the Collection will also remove the
corresponding mapping (key and value) from
the Map
Map.Entry Interface:

Each element is a map has a key and value. Each key-value pair is saved in a java.util.Map.Entry object. A set of these map entries can be
obtained by calling a map's entrySet( ) method. Iterating over a map is done by iterating over this set.

The Collections Framework provides three general-purpose Map implementation:

HashMap
TreeMap
LinkedHashMap

HashMap:
The HashMap is a class which is used to perform some basic operations such as inserting, deleting, and locatingelements in a Map .
The  java.util.HashMap class is implemented with and roughly equivalent to a Hashtable except that it is unsynchronized and permits null. It
works with the Iterators requires a well-defined implementation of the method hashCode( ).

TreeMap:
The TreeMap implementation is useful when you need to traverse the keys from a collection in a sorted manner. The elements added to a
TreeMap must be sortable in order to work properly. It is depend upon the size of the specified collection, it may be faster to add elements to
a HashMap , then convert the map to a TreeMap for traversing the sorted keys.

LinkedHashMap:
A LinkedHashMap is implemented using both Hash table and linked list implementation of the Map interface. This implementation differs
from HashMap that maintains a doubly-linked list running through all of its entries in it. The orders of its elements are based on the order in
which they were inserted into the set (insertion-order). 

The list of methods supported by Map interface are shown in the table given below:

Method Uses
 put(Object key, Associates the specified value with the
Object value) specified key in the map.
 clear( ) Removes all mappings from the map
Copies all of the mappings from the
 putAll(Map t)
specified map to the map.
Returns true if this map contains no
 isEmpty( )
key-value mappings.
Returns an Iterator object for the
 iterator( ) collection which may be used to
retrieve an object.
Removes the mapping for this key from
 remove(Object key)
this map if it is present.
 Returns a set view of the keys
 keySet( )
contained in this map.
 Returns a set view of the mappings
 entrySet( )
contained in this map.
 Returns a collection view of the values
 values( )
contained in this map.
Returns the number of key-value
 size( )
mappings in this map.
SortedMap Interface:

The Collection Framework provides a special Map interface for maintaining elements in a sorted
order calledSortedMap . The SortedMap interface extends the Map interface which maintains its elements in ascending order. Working
with a SortedMap is just similar to a SortedSet except, the sort is done on the map keys. In addition to
methods of  the Map interface, it provides two methods shown as:

firstKey( )
lastKey( ) 

The firstKey( ) method returns the first (lowest) value currently in the map while the lastKey( ) method returns the last (highest) value currently
in the map.

Let see an example implementing the HashMap and TreeMapclass.

import java.util.*;

public class MapDemo {

  public static void main(String args[]) { 
    String days[]={"Sunday", "Monday", "Tuesday", "Wednesnday",

                         "Thursday", "Friday", "Saturday"};

   Map map = new HashMap();

  try{

  for(int i=0; i<7; i++){

    map.put(i, days[i]);

  }

  

  TreeMap tMap=new TreeMap(map);

     //Rerieving all keys

    System.out.println("Keys of tree map: " + tMap.keySet());

    //Rerieving all values

    System.out.println("Values of tree map: " + tMap.values());

    //Rerieving the First key and its value

    System.out.println("First key: " + tMap.firstKey() + 

                  " Value: " + tMap.get(tMap.firstKey()) + "\n");

      

    //Removing the first key and value

    System.out.println("Removing first data: " 

                          + tMap.remove(tMap.firstKey()));

    System.out.println("Now the tree map Keys: " + tMap.keySet());

    System.out.println("Now the tree map contain: " + tMap.values() + "\n");

    //Rerieving the Last key and value

    System.out.println("Last key: " + tMap.lastKey() + 

                       " Value: " + tMap.get(tMap.lastKey()) + "\n");  

    //Removing the last key and value

    System.out.println("Removing last data: " + tMap.remove(tMap.lastKey()));

    System.out.println("Now the tree map Keys: " + tMap.keySet());

    System.out.println("Now the tree map contain: " + tMap.values());

  }

  catch(Exception e){}
  }

Output of this program:

C:\nisha>javac MapDemo.java

C:\nisha>java MapDemo
Keys of tree map: [0, 1, 2, 3, 4, 5, 6]
Values of tree map: [Sunday, Monday, Tuesday, Wednesnday,
Thursday, Friday, Saturday]
First key: 0 Value: Sunday

Removing first data: Sunday


Now the tree map Keys: [1, 2, 3, 4, 5, 6]
Now the tree map contain: [Monday, Tuesday, Wednesnday,
Thursday, Friday, Saturday]

Last key: 6 Value: Saturday

Removing last data: Saturday


Now the tree map Keys: [1, 2, 3, 4, 5]
Now the tree map contain: [Monday, Tuesday, Wednesnday,
Thursday, Friday]

C:\nisha>
The given program stores the values mapping with their keys to the map. The keySet( ) method retrieves all keys from the map and
the values( ) method retrieves all the values added to a map. The remove( ) method removes the key from the map with its value specified in it.

Java SE 6
       
The latest news for the java programmers that the Sun MicroSystems has released the Java SE 6 on Monday December 11. So go and grab your
copy.  It has been released with the promises to ease the complexities faced in the jdk 1.5. Here we at Roseindia.net is providing of each and
every new features added in jdk 6 with running examples. 

These are the major new Features in JAVA SE 6

1.New Features in JSE 6


This section introduces you with the new exciting features of Java SE 6.
   

2.Changes in I/O
This is a new feature added in Java SE 6, which has the ability to read text from a terminal without having it echo on the screen
through java.io.Console.   
  

3.Java 6.0 New Features (Collection Framework)


As the name indicates collections is a group of objects known as its elements. Basically it is a package of data structures that
includes ArrayLists, LinkedLists, HashSets, etc. A collection is simply an object that groups multiple elements into a single unit.
It is also called as a container sometimes. It is used to store, retrieve, manipulate, and communicate aggregate data. 

1. Introduction to Collections API 


A collection is simply an object that groups multiple elements into a single unit. It is also called
as a container sometimes. It is used to store, retrieve, manipulate, and communicate aggregate
data.
  
2. Introduction to Collections Framework
In this section, you will know about the collection framework as well as its advantages and
disadvantages. 
 
3. Introduction to Collection Interfaces
The Collections Framework is made up of different sets of interfaces for storing and
manipulating groups of data into a single unit. It consists of several interfaces, and classes that
implements those interfaces, within the java.utilpackage.

Collection Interface
Set Interface and SortedSet
List and Queue Interface
Map and SortedMap Interface
Collection Implementations
Collection Algorithms
Custom Collection Implementations
4. Java 6.0 Collection Framework
Some of the new collections APIs have been introduced in Java 6.0.
  
5. Collections Framework Enhancement
In Collection framework, we are able to improve the performance hashing function that is used
by java.util.HashMap. It provides some new Collection interfaces also.
Lets See How to Work With Collections Framework With the Help of Following
Examples.
1. Navigable Map Example
In NavigableMap we use methods to return the key value pair
like navMap.put(1, "January"); whereas in NavigableSet we use
methods to return values.
  
2. Navigable Set Example
In the example below we have used NavigableSet method to sort the elements in
ascending order, descending order, also to retrieve the element which is immediately
greater than or equal to 35 etc. 
 
3. HashSet Example
In this section provides you an example to HashSet collection frame
work.A HashSet is a set that doesn't allow duplicate elements and doesn't order or
position its elements.
  
4. Linked List Example
This section discusses an example to demonstrate the various methods
of List interface. We are using two classes ArrayList and LinkedList in
the example code.
 
5. Tree Map Example
In the following example, we have used the TreeMap method, which stores its
elements in a tree and orders its elements based on their values. Here in the example
we have used the key of the element to show the values of the element.
 
6. Tree Set Example
In the following example, we have used the TreeSet collection, which is similar
to TreeMap that stores its elements in a tree and maintain order of its elements based
on their values.
1.Changes in jar and zip
Jar and zip support has been enhanced in JDK 6. In this, two new compressed streams have been added. These
are java.util.zip.DeflaterInputStream  and java.util.zip.InflaterOutputStream.
  

2.Java Web Start enhancements in version 6


The cache format of Java Web Start and Plug-In has been fully changed. All dialogs have been redesigned and consolidated
between Java Web Start and Plug-In to be more user friendly.
  

3.JMX API Enhancements


Enhancements has been made to the JMX API in Java SE 6 like : JMX API now completely supports Generics, MXBeans have
been added and much more?
  

4.Java Platform Debugger Architecture Enhancements


JVMDI has been deleted in JAVA SE 6 and JPDA has been added. Some new Methods are included like boolean boolean
canGetInstanceInfo() and much more?
  

5.Java SE 6 Monitoring and Management Enhancements


API provided by JAVA SE allows you to monitor and manage the JVM in the package java.lang.management. JAVA SE 6 includes
some enhancement to this API.
  

6.New Package java.util.spi in JDK 6


A new package Java.util.spi has been included in JAVA SE 6.
  

7.Networking features and enhancements in Java SE version 6.0


This feature include enhancement in networkInterface, support for Internationalized Domain Names, HTTP Negotiate
Authentication and much more?
  

8.Enhancements in java.lang.Class and java.lang.reflect


Some new Methods are included in java.lang.Class like : getInterfaces(), getClasses(), getConsturctors(), getMethod(String,
Class?) and much more?.
  

9.Enhancement in RMI for JDKTM 6


java.rmi.MarshalledObject now support generics
  

10.JAVA SE 6 Security Enhancements


JAVA SE 6 has added support for some security functionality: the XML Digital signature API and implementation, Smart Card I/O
API. And much more? 
  

11.Serialization Changes and Enhancements in JAVA SE Development Kit 6


The new method ObjectStreamClass.lookupAny now used to obtain an ObjectStreamClass instance for a non-serializable Class
  

12.JavaTM Virtual Machine Technology


DTrace support has include in Java SE 6 HotSpot VM. The hotspot provider makes available probes that can be used to track the
lifespan of the VM, thread start and stop events
  
13.Scripting for the Java Platform
By using this Features developers integrate Java technology and scripting languages by defining a standard framework and
application programming interface (API)
 

14.Leveraging Security in the Native Platform Using Java SE 6 Technology


The JAVA SE 6 provide a large set of security APIs. These Security APIs span a wide range of areas, including cryptography
public key infrastructure, secure communication, authentication, and access control.

15.JAX-Web Services 2.0 With the Java SE 6 Platform


Most exciting new features of the JAVA SE 6 is support for the Java API for XML Web Services (JAX-WS), version 2.0.

16.What are New Features in JAVA SE 6


The articles highlights the new features and latest developments in the Java SE 6 which will make familiar to you with these
update features.

17.Java faqs
This section contains collection of frequently asked questions(faqs) in interview or viva of Java.

Collection Interfaces
       
The Collections Framework is made up of a set of interfaces  for storing and manipulating groups of data into a single unit. It consists of several
interfaces, and classes that implement those interfaces, contained within the java.util package. It provides tools for maintaining a data container
of objects. 

Different interfaces describe different types of functionalities.

The following diagrams shows the framework of core collection interfaces hierarchy.

Table of the ordered and unordered Collection interfaces shown as: 

 Interface  Allows  Maps key to


 Ordered
name duplicates object
 Collection  No  Yes  No
 Set  No  No  No
 List  Yes  Yes  No
 Map  No  No  Yes
 SortedSet  Yes  No  No
 SortedMap  Yes  No  Yes
Collection Interface:

The Collection interface is the root interface for the Java collections hierarchy. It is extended by the List, Set, and the SortedSet interfaces. The
Collection interface is used to represent a group of objects, or elements. Typically, it represents data items that form a natural group. Some
collection allows duplicate elements while others do not. It consists of both ordered and unordered elements.
 The declaration of the Collection interface is shown as:

public interface Collection<E>..

The <E> syntax tells that, the declared interface is a generic interface i.e. when you declare a Collection instance you should specify the type of
object contained in the collection.
This interface supports basic operations like adding and removing. When you try to remove an element, only a single instance of the element in
the collection is removed, if it is available. 

Following methods can be used for adding and deleting an element respectively.

boolean add(Object element)  


boolean remove(Object element)

The list of other methods belonging to the Collection interface is shown in the table given below

Method Uses
 add(E o)   Adds the specified element to this set if it is not
     already present (optional operation).
 
 clear()   Removes all of the elements from this set
(optional operation).
contains(Object o) Returns true if this set contains the specified
element.
 equals(Object o)   Compares the specified object with this set for
equality.
 hashCode()   Returns the hash code value for this set.
  isEmpty()    Returns true if this set contains no elements.
 iterator()   Returns an iterator over the elements in this set.
 remove(Object o)  Removes the specified element from this set if it
is present (optional operation).
 size()   Returns the number of elements in this set (its
cardinality).
Ads

Introduction to Collections Framework


       
Collections Framework:

The Collections Framework provides a well-designed set of interfaces and classes for storing and manipulating the groups of data into a single
unit. The collections framework is a unified architecture which is used to represent and manipulate collections. The framework allows the
collections to get manipulated independently, additionally it reduces the programming efforts and increases performance.

It includes implementation of interfaces and algorithms. Basically it is a unified architecture that consists the following collections:  

1.Interfaces: These are the abstract data types that represent collections. With the help of interfaces we  manipulate collections
independently. A hierarchy is generally formed with interfaces in object-oriented languages.
2.Implementations: They are the reusable data structures with the concrete implementations of the collection interfaces.
3.Algorithms: Algorithms are used to perform computations, such as searching, sorting etc on the objects that implement collection
interfaces. They provide reusable functionality i.e. the same method can be used with different implementations of the collection
interfaces. Hence they are also said to be polymorphic.  
4.General-purpose Implementations: These are the primary implementations of the collection interfaces.  
5.Infrastructure: Interfaces that provide essential support for the collection interfaces.  
6.Array Utilities: Utility functions for arrays of primitives and reference objects.
This functionality was added to the Java platform as a part of the Collections Framework. 
Advantages of collections framework:

The Java Collections Framework provides the following benefits:

1.Reduces the efforts to learn and use the new APIs: We need not to learn multiple ad hoc collection APIs.  
2.Fosters software reuse: It provides a standard interface for collections that fosters software reuse and also provides algorithms to
manipulate them.  
3.Reduces the efforts to design new APIs: It reduces the efforts required to design and implement APIs by eliminating the need to
produce ad hoc collections APIs.  
4.Reduces the programming efforts: It provides useful data structures and algorithms that reduces programming efforts due to which
we need not to write them ourselves.  
5.Increases performance: It provides high-performance implementations of useful data structures and algorithms that increases the
performance.
6.Provides interoperability between the unrelated APIs: It helps in establishing a common language to pass collections back and
forth to provide interoperability between the unrelated APIs.
7.Provides resizable capability: Collection is resizable i.e.  it can grow dynamically.
Disadvantages of collections framework:

1.It must cast to correct type.


2.avoids the compile-time type checking.

Enhancements in Networking Features


         
Changes in NetworkInterface Class

NetworkInterface is a class in java.net package. This class is used to represent a Network Interface and it is made up of a name and a IP addresses
list assigned to this interface. In Java 6, this class provides some new methods for accessing state and configuration information and this
information is related to system's network adapters. This includes information like broadcast address, list object with all or a subset of the
InterfaceAddress, enumeration object with all of the subinterfaces, subnet mask, hardware address (MAC addresses) and MTU size.

Some new methods are added in NetworkInterface class are as follows:

public boolean isUp()


Above method returns true if the network interface is up and running. Up specifies that routing entries have been set up for the network
interface. And running specifies that required system resources have been allocated.
public boolean isLoopback()
Above method returns true if the network interface is a loopback interface.
public boolean isPointToPoint()
Above method returns true if the network interface is point to point interface.
public boolean supportsMulticast()
Above method is used to know the network interface is support multicasting or not. If yes then its return true.
public byte[] getHardwareAddress()
Above method is used to get the byte array of MAC address. It return null if the address is not accessible or doesn't exist.
public int getMTU()
Above method returns the value of MTU (Maximum Transmission Unit) of this interface.
  Above all methods throws an SocketException if an I/O error occurs.
public boolean isVirtual()
Above method return true if the network interface is virtual interface. Virtual interfaces are those interfaces that created as child of
physical interface and given different settings such as MTU or address.
public List<InterfaceAddress> getInterfaceAddresses()
Above method is used to get a list object of all or a subset of the InterfaceAddresses of this network interface. If security manager is
available, it invoke its checkConnect() for each InterfaceAddress with the InetAddress. Only those InterfaceAddresses will be returned
in the list where the checkConnect() doesn't throw a SecurityException.
public Enumeration<NetworkInterface> getSubInterfaces()
Above method is used to get an enumeration object with all of the virtual interfaces (subinterfaces) of this network interface.
public NetworkInterface getParent()
Above method is used to get the parent NetworkInterface of this network interface but only when if it is a subinterface. It returns null if
it has no parent or it is a physical interface. 
InterfaceAddress Class

A new class InterfaceAddress is also included in java.net package. This class is used to represent a Network Interface address. And its
encapsulates all information about a NetworkInterface's IP addresses including the subnet mask and broadcast address.

Following methods are included in this class:

public InetAddress getAddress()


Above method returns an InetAddress of the given Interface Address.
public InetAddress getBroadcast()
Above method returns an InetAddress representing the broadcast address for this interface address. It returns null if there is no
broadcast address. Only IPv4 networks have broadcast address.
public short getNetworkPrefixLength()
Above method returns the network Prefix length for the subnet mask of the interface address.
The following example demonstrates the above methods:

import java.util.*;

import java.net.*;

public class NetInt

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

Enumeration<NetworkInterface> netis=

NetworkInterface.getNetworkInterfaces();

while(netis.hasMoreElements())

NetworkInterface nis=netis.nextElement();

System.out.println("Network Interface name is :"

+nis.getName());

System.out.println("Display name of network interface is :"

+nis.getDisplayName());

System.out.println("Network Interface is up and running :"

+nis.isUp());

System.out.println("Network Interface is loopback :"

+nis.isLoopback());

System.out.println("Network Interface is point to

point interface :"+nis.isPointToPoint());

System.out.println("Network Interface support multicasting :"


+nis.supportsMulticast());

System.out.println("Network Interface MTU value is :"

+nis.getMTU());

System.out.println("Network Interface is virtual interface :"

+nis.isVirtual());

System.out.println("Network Interface has any Paren :"

+nis.getParent());

byte[] haddress=nis.getHardwareAddress();

if (haddress!= null)

System.out.print (" Hardware address = ");

for (int i = 0; i < haddress.length; i++)

System.out.printf ("%02X%c", haddress [i],

(i != haddress.length-1) ? '-' :'\0');

System.out.println();

List<InterfaceAddress> iaddress=nis.getInterfaceAddresses();

Iterator<InterfaceAddress> iiaddress=iaddress.iterator();

while(iiaddress.hasNext())

InterfaceAddress iadd=iiaddress.next();

System.out.println("Interface Address -");

System.out.println("InetAddress of the Interface Address :"

+iadd.getAddress());

System.out.println("Broadcast Addres of the Interface Address :"

+iadd.getBroadcast());

System.out.println("Network Prefix Length of the Interface Address :"

+iadd.getNetworkPrefixLength());

System.out.println();

 Output of the program is:  


C:\j2se6>javac NetInt.java

C:\j2se6>java NetInt
Network Interface name is :lo
Display name of network interface is :MS TCP Loopback
interface
Network Interface is up and running :true
Network Interface is loopback :true
Network Interface is point to point interface :false
Network Interface support multicasting :true
Network Interface MTU value is :1520
Network Interface is virtual interface :false
Network Interface has any Paren :null
Interface Address -
InetAddress of the Interface Address :/127.0.0.1
Broadcast Addres of the Interface
Address :/127.255.255.255
Network Prefix Length of the Interface Address :8

Network Interface name is :eth0


Display name of network interface is :3Com 3C920
Integrated Fast Ethernet Contro
ller (3C905C-TX Compatible) - Packet Scheduler
Miniport
Network Interface is up and running :true
Network Interface is loopback :false
Network Interface is point to point interface :false
Network Interface support multicasting :true
Network Interface MTU value is :1500
Network Interface is virtual interface :false
Network Interface has any Paren :null
Hardware address = 00-B0-D0-3A-71-F7
Interface Address -
InetAddress of the Interface Address :/192.168.10.55
Broadcast Addres of the Interface
Address :/192.168.10.255
Network Prefix Length of the Interface Address :24
Java Web Start Enhancements in version 6
       

Enhancements in Java Web Start 


JNLP Specification addition of the <update> element - The <update> element with its attributes "policy" and "check" is now
supported. It describes the applications preferences for how Java Web Start should check for updates on the web, and what to do when
it is known before starting the application that there is an update available.
  
Prior to Java SE 6, In Java Web Start <offline-allowed> element was overloaded for two things. First, the application can run in offline
mode. Second, Try to check for updates before running an application (when not run in offline mode) could time out. When a times out,
the application would launched to the cache wile and the updates check continued in the background.
   
In Java SE 6, the "policy" attribute of <update> element is used to determine what to do when it is known before launching the
application that an update is available. The values of policy attribute can be "always" (default value), "prompt-update" or "prompt-run".
Because of "check" attribute of <update> element in version 6, the <offline-allowed> element has no more its second meaning that
discussed above. Default values : <update check="timeout"/> has same behavior was specified by <offline-allowed> in previous
version. Whenever <offline-allowed> was previously used, for that behavior you need to specify <update check="always"/>. A <update
check="background"/> can be specified to always immediately launch from the cache while spawning a check for update in the
background.
 

JNLP Specification relaxation is required for the DownloadService API - Upto now we used to pass the URLs as arguments to all
APIs were restricted to be used a URLs to resources listed in the jnlp files. In this version there is not any such restrictions for signed
and trusted code there is no restriction on untrusted code that it has to be listed in the jnlp files but the only requirement is that it should
be from the same codebase. 
  
But in current version, URLs to jnlp files are allowed, so that by using DownloadService.removeResource() you can remove a whole
application from cache and by using DownloadService.load Resource() you can import an application. Due to this change now
resources is not listed in jnlp file can now be used in an application.
 

SocketService Implementation - A clarification in the definition of the sandbox is also a another important specification change, that
is only the default sandbox, this implementation is free to prompt the user to allow actions that are not allowed by the sandbox. In Java
1.5, it was done for printing, so that in AWT by using printing API, you can expand the sandbox for allowing the application to access
the printer. But in Java SE 6, it is done for socket connection, that's why if an untrusted application try to connect to a url, the user can
be prompted to allow the connection.
 

Replace <j2se> element by new <java> element in JNLP file - This element will be used only with Java Web Start version 6 for jnlp
files. The <j2se> element is replaced by <java>tag (The main reason of behind that is only the Java Platform Standard Edition is no
longer known as j2se).
 

Enhanced <association> element now contain the <icon> and <description> sub-elements - When creating file extension and
mime type associations with Java Web Start application, you can specify description and a separate icon to be used for each association.
  

JNLP is now an instance of the URLClassLoader - It gives some powerful advantages. First, Jar indexing is now fully supported. If
you want to create a jar index of several jar file in the main jar file that indexes all the jar files, and then you can mark each additional
jar as lazy, and it can be download only when a resource or class in it is referenced. Second, The JNLPClassLoader was rewritten to
extend URLClassLoader. For getting a list of jar elements that are listed in the jnlp files an application can invoke getURLs(). The URL
returned for calls to Class Loader.getResource() is proper Jar URL of the item on the net. By extending URLClassLoader, it allows Java
Web Start to operate without caching.
 

Java Web Start now supports icon formats - Now, two icon formats "png", "ico" are supported by Java Web Start. This
enhancement allows to specify an icon that would not be translated into a different format depending on its use. Now you can specify a
icon format kind="shortcut" with width and height attributes. Example - <icon kind="shortcut" href="desktopshortcut.ico" width="32"
height="32"/> <icon kind="shortcut" href="menushortcut.ico" width="16" height="16"/>. For destktop shortcuts use the icon size is
closer to 32 x32 and for menu shortcut its closer to 16 x 16.
 

Add/Remove entries will now supported on Windows for Java Web Start - Add/Remove entries will now include will now include
the publisher, install date, publisher websight and application icon from the jnlp file information block.
 

Desktop shortcut tooltips - Java Web Start creates a Desktop shortcuts. In Jnlp file Java Web Start will use the <description> element
to create a tooltip for describing the application.
 

Enhanced JNLPDownloadServlet - Now, the enhanced JNLPDownloadServlet contains the two macro $$hostname and a $$sight.
The expanded $$hostname contains the host name and $$sight contains the web site address without the WAR context portion.
  

The safe vm args and properties list has been enhanced and some Command Line Interface (CLI) items are also changed or added.  

Java Web Start and Java Plug-in Common Enhancements


Cache and System Format
In Java SE 6, the cache format has been fully changed. That's why, any existing code using previous format of cache for Java Web Start
or Java Plug-in will no longer work. Existing applications cache will be upgraded and converted to the new format of cache when the
first time you launch a Java Web Start application, or by launching the cache viewer using javaws-viewer. And System cache will
upgraded when the first time you run Java Web Start application in system mode, or just launching javaws - system.

Download Engine and Cache Consolidation


Download Engine and entire caching mechanism are redesigned and consolidated between Java Web Start and Java Plug-in. This
include some new features in Java Web Start:

By using Java Control Panel it allow to disable the caching.

The maximum cache size set in Java Control Panel is supported in Java Web Start.

A cleanup thread can be started by Java Web Start to removed Least Recently Used (LRU) items from the cache when
approaching the maximum size.

The <no-cache> directive is now supported. When using this directive, and update check is made to verify the cached
contents is same as at the URL.

The expiration-date is supported. If any download resource contains an expiration date, it will not be used after that date.
 

Secure Versioning
In Java SE 6, signed Java Web Start applications are not affected but the unsigned Java Web Start applications specify a version trigger
a security warning, requiring explicit user permission before running the application.
  

Other Enhancements

All dialogs and screens have been redesigned by user experience team to be more user friendly and accessible.

Now, Java Console is not included in modality. In Java 6, some new features are added in modality by AWT. By this you
can interact with Java Console even when the application is displaying a modal dialog.

CRL (Certificate Revocation Lists) and OCSP (Online Certificate Status Protocol) are supported by Java Web Start and Java
Plug-in for verifying the certificates.

SSL/TSL are supported by Java Web Start and Java Plug-in. An option has been provided by Java Control Panel to select the
default SSL handshaking protocol. The default is set to SSLv3 and SSLv2, but then user can change it to TSL.

Changes in Jar and Zip


       
In Java SE 6 there are two changes in jar command behavior:
Before Java SE 6, the timestamps (date and time) of extracted files by jar command are those listed the current time means extraction
time instead of archive file time. But other de/compression tools use the archive time. So in Java SE 6, they do a change in jar
command behavior that is the date and time of extracted files by jar command were the archive time. But if the old behavior is needed,
use sun.tools.jar.useExtractionTime=true 

At the time of creating a jar, we have the ability in executable jar file to specify the entry point for stand-alone application bundle. The
'e' option declare the entry point through creating or overriding the Main-Class attribute value in the jar file's manifest.
There are some changes in ZIP File also:

Number of open ZIP files - Prior to Java SE 6, we faced the limitation on the number of concurrently open ZIP files in Microsoft
Windows. And the maximum used to be 2306 but now this limitation has removed and the maximum used is depend on the whatever
the platform will support.
Number of entries in a ZIP file - The ZIP file format was using 2-byte field to record the number of entries in the file, imposing a
64K limit. But in Java SE 6, ignores that field, just counts the entries. Before Java 6 you could count the entries
with ZipInputStream or ZipFile, but if there were more than 64 entries in the file you get the different result.
ZIP File Names - Java SE 6 support the file names longer than 256 characters.
API Changes -  There are two new compressed streams have been added :

1.java.util.zip.DeflaterInputStream - This stream is used to read the compressed data. For example, This stream can be useful if any
client  want to send the data in compressed form over a network and it can compressed into packets by DeflaterInputStream.
2.java.util.zip.InflaterOutputStream - This stream is used to write the decompressed data. For example, At the receiving end
decompresses the compressed packet by writing to an InflaterOutputStream.

New Features of JAVA SE 6.


       
Following are the new features in SE 6.

1.Changes in I/O
This is a new feature added in Java SE 6, which has the ability to read text from a terminal without having it echo on the screen
through java.io.Console.
  

2.Collections Framework Enhancement


In Collection framework, we are able to improve the performance hashing function that is used by java.util.HashMap. It provides
some new Collection interfaces also.
  

3.Changes in jar and zip


Jar and zip support has been enhanced in JDK 6. In this, two new compressed streams have been added. These are
java.util.zip.DeflaterInputStream and java.util.zip.InflaterOutputStream.
  

4.Java Web Start enhancements in version 6


The cache format of Java Web Start and Plug-In has been fully changed. All dialogs have been redesigned and consolidated
between Java Web Start and Plug-In to be more user friendly.
  

5.JMX API Enhancements


Enhancements has been made to the JMX API in Java SE 6 like : JMX API now completely supports Generics, MXBeans have
been added and much more?
  

6.Java Platform Debugger Architecture Enhancements


JVMDI has been deleted in JAVA SE 6 and JPDA has been added. Some new Methods are included like boolean boolean
canGetInstanceInfo() and much more?
  

7.Java SE 6 Monitoring and Management Enhancements


API provided by JAVA SE allows you to monitor and manage the JVM in the package java.lang.management. JAVA SE 6 includes
some enhancement to this API.
  
8.New Package java.util.spi in JDK 6
A new package Java.util.spi has been included in JAVA SE 6.
  

9.Networking features and enhancements in Java SE version 6.0


This feature include enhancement in networkInterface, support for Internationalized Domain Names, HTTP Negotiate
Authentication and much more?
  

10.Enhancements in java.lang.Class and java.lang.reflect


Some new Methods are included in java.lang.Class like : getInterfaces(), getClasses(), getConsturctors(), getMethod(String,
Class?) and much more?.
  

11.Enhancement in RMI for JDKTM 6


java.rmi.MarshalledObject now support generics
  

12.JAVA SE 6 Security Enhancements


JAVA SE 6 has added support for some security functionality: the XML Digital signature API and implementation, Smart Card I/O
API. And much more? 
  

13.Serialization Changes and Enhancements in JAVA SE Development Kit 6


The new method ObjectStreamClass.lookupAny now used to obtain an ObjectStreamClass instance for a non-serializable Class
  

14.JavaTM Virtual Machine Technology


DTrace support has include in Java SE 6 HotSpot VM. The hotspot provider makes available probes that can be used to track the
lifespan of the VM, thread start and stop events
  

15.Scripting for the Java Platform


By using this Features developers integrate Java technology and scripting languages by defining a standard framework and
application programming interface (API)
 

16.Leveraging Security in the Native Platform Using Java SE 6 Technology


The JAVA SE 6 provide a large set of security APIs. These Security APIs span a wide range of areas, including cryptography
public key infrastructure, secure communication, authentication, and access control.

17.JAX-Web Services 2.0 With the Java SE 6 Platform


Most exciting new features of the JAVA SE 6 is support for the Java API for XML Web Services (JAX-WS), version 2.0.

Changes in I/O
       
This is a new feature added in Java SE 6, which has the ability to read text from a terminal without echoing on the screen. This functionality is
provided by java.io.Console Class which is newly added in JAVA SE 6.

Reading passwords without echoing their text


JAVA SE 6 has the new ability to read text from a terminal without echoing on the screen, through new class java.io.Console.

Console Class 
Console is a new class which is included in JAVA SE 6. It is the advanced alternative to the Standard Streams. Its a single, predefined object of
Console type that provide most of the same features as by Standard Streams, and others besides. The Console is particularly useful for secure
password entry. The Console object provides input and output streams which is true character stream. 

Console c=System.console();

Before using the Console, you must retrieve the Console object by invoking System.console(). This method returns the object if it is available. But
if it returns NULL, then Console operations are restricted, because the OS doesn?t support them or the program was executed in non-interactive
environment.
Through the readPassword method, the Console object support secure password entry. This method helps in two ways. First, it suppresses
echoing, so the password is not visible on the screen. Second, readPassword returns a character array, not a String, so the password can be
overwritten, removing it from memory as soon as it is no longer needed.

The Following program is for changing the user?s password and the following code demonstrates several Console methods:

import java.io.Console;

import java.util.Arrays;

import java.io.IOException;

public class UseConsole{

static char [] oldPass;

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

Console c = System.console();

if (c == null) {

System.err.println("Console Object is not available.");

System.exit(1);

String login = c.readLine("Enter your login Name: ");

oldPass = c.readPassword("Enter your Existing password: ");

if (check(login, oldPass)) {

boolean flag;

do {

char [] newPass1 =

c.readPassword("Enter your new password: ");

char [] newPass2 =

c.readPassword("Enter new password again: ");

flag = !Arrays.equals(newPass1, newPass2);

if (flag) {

c.format("Mismatch the Passwords. Please try again.%n");

} else {

change(newPass1);

c.format("Password for %s has changed.%n", login);

Arrays.fill(newPass1, ' ');

Arrays.fill(newPass2, ' ');

} while (flag);
}

//check method.

static boolean check(String login, char[] password) {

return true;

//change method.

static void change(char[] password) {

oldPass=password;

Above Example follows these steps: 


1. Retrieving the Console object by invoking System.console(). But if the object is not available then abort from the program.
2. After getting the object invoke Console.readLine method to prompt for and read the user's login name. 
3. Invoke Console.readPassword to prompt for and read the user's existing password. 
4. Invoke check() to confirm that the user is authorized to change the password or not.
5. Repeat these three following steps until the user enters the same password twice: 
  · Invoke Console.readPassword method twice to prompt for and read a new password. 
  · If the user entered the same password both times, invoke change() to change the password. 
  · Overwrite both passwords with blanks by invoking Array.fill(). 

Output of the program is:

C:\j2se6>javac
UseConsole.java 

C:\j2se6>java UseConsole
Enter your login Name: rahul
Enter your Existing password:
Enter your new password:
Enter new password again:
Mismatch the Passwords.
Please try again.
Enter your new password:
Enter new password again:
Password for rahul has
changed.

C:\j2se6>
Download this example.
Some new methods are also added in File are as follow:

  Following methods are used to retrieve the information about disk usage: 
  o getTotalSpace() This method returns the partition size in bytes 
  o getFreeSpace() This method returns the unallocated bytes of the partition 
  o getUsableSpace() This method returns the available bytes of the partition with write permission checks and OS restriction 
The following example demonstrates the above methods:
import java.io.File;

public class FileMethod {

public FileMethod() {

File file = new File("C:");

System.out.println("C:");

System.out.println("Total Space: " + file.getTotalSpace());

System.out.println("Free Space: " + file.getFreeSpace());

System.out.println("Usable Space: " + file.getUsableSpace());

file = new File("C:\\windows");

System.out.println("\nC:\\windows (exist)");

System.out.println("Total Space: " + file.getTotalSpace());

System.out.println("Free Space: " + file.getFreeSpace());

System.out.println("Usable Space: " + file.getUsableSpace());

file = new File("D:\\windows");

System.out.println("\nD:\\windows (not exist)");

System.out.println("Total Space: " + file.getTotalSpace());

System.out.println("Free Space: " + file.getFreeSpace());

System.out.println("Usable Space: " + file.getUsableSpace());

public static void main(String[] args) {

new FileMethod();

 Output of the program is:  


C:\j2se6>javac
FileMethod.java 
C:\j2se6>java
FileMethod 
C: 
Total Space:
10238640128 
Free Space:
6918594560 
Usable Space:
6918594560 

C:\windows (exist) 
Total Space:
10238640128 
Free Space:
6918594560 
Usable Space:
6918594560 

D:\windows (not exist) 


Total Space: 0 
Free Space: 0 
Usable Space: 0 

C:\j2se6> 
Download this example.

The Following new methods are used to set file permissions: 

public boolean setWritable(boolean writable, boolean ownerOnly) and public booleansetWritable(boolean writable) set the


owner's or  everybody's write permission.

In above methods, if writable parameter is true then it sets the permission to allow the write operations but if it is false then write
operations is restricted.
If ownerOnly parameter is true then it sets the permission to allow write operation only to owner?s, but it is false then write operations
sets to everybody. But if the file system can not distinguish between owner and others then permission allow the operations to
everybody.
public boolean setReadable(boolean readable, boolean ownerOnly) and public booleansetReadable(boolean readable) set the
owner's or everybody's read permission 

In above methods, if readable parameter is true then it sets the permission to allow the read operations but if it is false then read
operations is restricted.
If ownerOnly parameter is true then it sets the permission to allow read operation only to owner?s, but it is false then read operations
sets to everybody.
public boolean setExecutable(boolean executable, boolean ownerOnly) and public booleansetExecutable(boolean executable) set
the owner's or everybody's execute permission.

In above methods, if executable parameter is true then it sets the permission to allow the execute operations but if it is false then
execute operations is restricted.
If ownerOnly parameter is true then it sets the permission to allow execute operation only to owner?s, but it is false then execute
operations sets to everybody.
public boolean canExecute() This method is using to tests the value of the execute permission. This method returns true if and only if
the pathname is exists and the application can execute the file.

Introduction to Collections API


       
As the name indicates, collections is a group of objects known as its elements. Basically it is a package of data structures that
includes ArrayLists, LinkedLists, HashSets, etc. A collection is simply an object that groups multiple elements into a single unit. It is also called
as a container sometimes. It is used to store, retrieve, manipulate, and communicate aggregate data. Typically, it represents data items that form a
natural group and allows duplicate elements while others do not. It consists of both ordered and unordered elements. There is no direct
implementation of this interface however SDK provides implementations of more specific sub interfaces like Set and List. The manipulation and
passing of collections is done by this interface.

The Two "standard" constructors should be provided by all the general-purpose Collection implementation classes. These classes typically
implement Collection indirectly through one of its sub interfaces.

1.Void (no arguments) constructor which creates an empty collection.


2.Constructor with a single argument of type Collection, which creates a new collection with the same elements as its argument.

The user can copy any collection using void constructor to produce an equivalent collection of the desired implementation type. As interfaces
cannot contain constructors there is no way to enforce this convention. However all of the general-purpose Collection implementations comply
this in the Java platform libraries.  

The Java Collections API:

Java Collections of API (Application Programming Intreface) Consists of several interfaces, and classes that implement those interfaces, within
the java.util package. It provides tools for maintaining a data container of objects. Each primitive value must be wrapped in an object of its
appropriate wrapper class (Boolean, Character, Integer, Double, etc.) to maintain a collection of primitive data. It is an
alternative tool to the creation of custom data structures.

You must be familiar with collections if you have worked with Java programming language . Collection implementations
included Vector, Hashtable, and array are available in earlier (pre-1.2) versions of the Java platform, but those versions do not include the
collections framework. Hence the new version of the Java platform contains the collections framework.

Advantages and Disadvantages of the Collection


Framework
       
In this section, you will learn the advantages and disadvantages of Java Collection Framework. A collection is simply an object that groups
multiple elements into a single unit. It is also called as a container sometimes. It is used to store, retrieve, manipulate, and communicate aggregate
data. Typically, it represents data items that form a natural group and allows duplicate elements while others do not. It consists of both ordered and
unordered elements. 

Advantages of collections framework:

1.We need not to learn multiple ad hoc collection APIs.


2.It provides a standard interface for collections that fosters software reuse and also provides algorithms to manipulate them.
3.Reduces the effort required to design and implement APIs by eliminating the need to produce ad hoc collections APIs.
4.It provides useful data structures and algorithms that reduces programming effort due to which we need not to write them ourselves.
5.It provides high-performance implementations of useful data structures and algorithms that increases the performance.
6.Helps in establishing a common language to pass collections back and forth that provides
interoperability between unrelated APIs.
7.Collection is resizable and can grow.
Disadvantages of collections framework:
1.It must cast to correct type.
2.It can't be done compile-time type checking.

Java 6.0 Collection Framework


       
 Some of the new collections APIs have been introduced in Java 6.0. These are:
1.Deque: It is used to represent Double ended queue. With the help of this collection we can add or remove elements at both the ends.
Deque implementation can be used as Stack (Last in first out) or Queue (First in First Out). There are two methods in Deque, which
are used for insertion, retrieval and removal of elements. One returns status or special value for each operation and the other will throw
exception if it fails in an operation.
2.BlockingDeque: It is similar to Deque but with added functionality. When we try to insert an element in a BlockingDeque and if the
BlockingDeque is already full then the element can wait till the space becomes available to insert an element. There are four methods
available for BlockingDeque.
Methods throws exception
Methods that times out (Waits for a given time for space to available)
Methods that blocks (Waits indefinitely for space to available)
Methods returns special value
3.NavigableSet: It is used to return the closest matches of elements. For instance if we want retrieve the element, which is immediately
greater than, or lower than element 20 or if we want to retrieve all elements greater than or lower than 35 from sorted set elements
[10,20,35,5] we can use NavigableSet methods that becomes just a method call. ConcurrentSkipListSet is one of the class that
implements NavigableSet.
4.NavigableMap: In NavigableSet, methods use to return values, but in NaviagableMap methods used to return the key,value
pair. ConcurrentSkipListMap is the one of the class which implements NaviagableMap
Some of the new Classes are: 

1.ArrayDeque: ArrayDeque is a class that implements Deque. If used as a stack or linked list, it performs much faster than before. It is
neither thread safe nor has capacity restrictions.
2.LinkedBlockingDeque: It implements BlockingDeque. Maximum capacity can be specified by using BlockingDeque interface.
However the maximum capacity will be Integer.MAX_VALUE if not specified.
3.ConcurrentSkipListSet: ConcurrentSkipListSet is one of the class that implements NavigableSet. It is used to return the closest
matches of elements.
4.ConcurrentSkipListMap: ConcurrentSkipListMap is the one of the class which implements NaviagableMap. In NavigableSet,
methods use to return values.
5.AbstractMap.SimpleEntry: The key value pair of one single entry in a Map is held by the instance of this class. Moreover it is a
static nested class nested inside abstractMap class. 
 
6.AbstractMap.SimpleImmutableEntry: This class is similar
to AbstractMap.SimpleEntry class however it has one difference that it throws the
exception UnsupportedOperationException when we try to set a value
while AbstractMap.SimpleEntry doesn?t.
Updated Classes in Java 6.0

1. LinkedList
 

2.TreeSet
 

3.TreeMap
 

4.Collections

Modified classes  

To implement the new interfaces we modify some classes like TreeSet is modified to implement NavigableSet, LinkedList is modified to
implement Deque, TreeMap is modified to implement NavigableMap etc. Some of the new methods
like newSetFromMap and asLifoQueue have been added to Collections 2.

 Hence the bi- directional traversal has become easier with java6.0 collections. We can even retrieve elements as desired.

Collections Framework Enhancements


       
In Collection framework, we are able to improve the performance hashing function that is used byjava.util.HashMap. It provides some new
Collection interfaces also.

Following new Interfaces and Classes are provided in JAVA SE 6 :

Deque ? Deque is a interface. It is a short for ?Double Ended Queue?. This interface defines some methods that access the element at
both ends. That means by the methods of this interface we can add and remove the elements at both ends.
ArrayDeque ? ArrayDeque Class implements a Deque interface. This class have no capacity restriction, it can grow according to
usage. If the external Synchronization is not available then it don?t support concurrent access by multiple thread.
Constructors Details :
public ArrayDeque()
Above Constructor is used to make a empty array deque with an default capacity that 16 elements.
public ArrayDeque(int numElements)
Above Construtor is used to make a empty array deque with the initial capacity that is sufficient to hold the specified elements.
public ArrayDeque<Etype>()
Etype is the type of the elements that held in this Collection. Above Constructor is used to make a array deque containing elements of
specified type.
Methods Details :

void addFirst(Etype e)
Above method is used to insert the element at the starting point of the array deque
void addLast(Etype e)
Above method is used to insert the element at the end point of the array deque.
  Above two methods throws following Exception:
i. IllegalStateException ? Due to capacity restriction the element cannot be added.
ii. ClassCastException ? Class of the specified element prevents it from being added to this deque
iii. NullPointerException ? If specified element is null.
iv. IllegalArgumentException ? If element having some property that prevent it from being added to this deque
boolean offerFirst(Etype e)
Above method is also used to insert the specified element at the starting point of the array deque. This method is preferable when we
using a capacity restricted deque. When element is added in array deque then its return true else it return false.
boolean offerLast(Etype e)
Above method is also used to insert the specified element at the end point of the array deque. This method is preferable when we using
a capacity restricted deque. When element is added in array deque then its return true else it return false.
  Above two methods throws following Exception: 
i.ClassCastException ? Class of the specified element prevents it from being added to this deque.
ii.NullPointerException ? If specified element is null.
iii.IllegalArgumentException ? If element having some property that prevent it from being added to this deque.
Etype removeFirst()
Above method is used to remove the first element of the array deque. And we can also retrieve this element. But if array deque is empty
then it throws a NoSuchElementException.
Etype removeLast()
Above method is used to remove the last element of the array deque. And we can also retrieve this element. But if array deque is empty
then it throws a NoSuchElementException.
Etype pollFirst()
Above method is same as removeFirst(). It is also used to retrieve and remove the first element of the deque. But it does not throws any
Exception even the deque is empty, its only return null.
Etype pollLast()
Above method is same as removeLast(). It is also used to retrieve and remove the last element of the deque. But it does not throws any
Exception even the deque is empty, its only return null.
Etype getFirst()
Above method is used just for retrieving the first element of deque. But if array deque is empty then it throws a
NoSuchElementException.
Etype getLast()
Above method is used just for retrieving the last element of deque. But if array deque is empty then it throws a
NoSuchElementException.
Etype peekFirst()
Above method is same as getFirst().It is also used to retrieving the first element of the deque. But it does not throws any Exception even
the deque is empty, its only return null.
Etype peekLast()
Above method is same as getLast().It is also used to retrieving the last element of the deque. But it does not throws any Exception even
the deque is empty, its only return null.
boolean removeFirstOccurrence(Object obj)
Above method is used to remove the first occurrence of the specified element. It return true when the specified element was remove.
But if the deque does not contain the specified element it is unchanged.
boolean removeLastOccurrence(Object obj)
Above method is used to remove the last occurrence of the specified element. It return true when the specified element was remove. But
if the deque does not contain the specified element it is unchanged.
The following example demonstrates the above methods:
import java.io.*;

import java.util.*;

public class NewDeque

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

Console c=System.console();

if(c==null)

System.err.println("Console object is not available");

System.exit(1);

ArrayDeque<String> dqname = new ArrayDeque<String>();

String name = null;

name = c.readLine("Enter any String: ");

dqname.add(name);

show(dqname);

name=c.readLine("Enter any string to add on starting

point of deque by addFirst():");

dqname.addFirst(name);

show(dqname);

name=c.readLine("Enter any string to add on ending

point of deque by addLast():");

dqname.addLast(name);

show(dqname);

name=c.readLine("Enter any string to add on starting

point of deque by offerfirst() :");

dqname.offerFirst(name);

show(dqname);

name=c.readLine("Enter any string to add on ending

point of deque by offerlast() :");

dqname.offerLast(name);
show(dqname);

System.out.println("Getting the first element

by using getFirst()");

String str1=dqname.getFirst();

System.out.println("First element is : "+str1);

System.out.println("Getting the Last element by using

getLast()");

str1=dqname.getLast();

System.out.println("Last element is : "+str1);

System.out.println("Getting the first element by

using peekFirst()");

str1=dqname.peekFirst();

System.out.println("First element is : "+str1);

System.out.println("Getting the Last element by

using peekLast()");

str1=dqname.peekLast();

System.out.println("Last element is : "+str1);

System.out.println("Removing the first element

by using removeFirst()");

str1=dqname.removeFirst();

show(dqname);

System.out.println("Removing the Last element

by using removeLast()");

str1=dqname.removeLast();

show(dqname);

System.out.println("Removing the first element

by using pollFirst()");

str1=dqname.pollFirst();

show(dqname);

System.out.println("Removing the Last element

by using pollFirst()");

str1=dqname.pollLast();
show(dqname);

static void show(ArrayDeque<String> dqname)

Iterator<String> nameIter = dqname.iterator();

while(nameIter.hasNext())

System.out.println(nameIter.next());

Output of the program is:  

C:\j2se6>javac NewDeque.java

C:\j2se6>java NewDeque
Enter any String: Rose
Rose
Enter any string to add on starting point of deque
by addFirst():India
India
Rose
Enter any string to add on ending point of deque
by addLast():Net
India
Rose
Net
Enter any string to add on starting point of deque
by offerfirst() :Com
Com
India
Rose
Net
Enter any string to add on ending point of deque
by offerlast() :Chandan
Com
India
Rose
Net
Chandan
Getting the first element by using getFirst()
First element is : Com
Getting the Last element by using getLast()
Last element is : Chandan
Getting the first element by using peekFirst()
First element is : Com
Getting the Last element by using peekLast()
Last element is : Chandan
Removing the first element by using removeFirst()
India
Rose
Net
Chandan
Removing the Last element by using removeLast()
India
Rose
Net
Removing the first element by using pollFirst()
Rose
Net
Removing the Last element by using pollFirst()
Rose

Navigable Map Example


       
We already know that NavigableMap is similar to NavigableSet. In NavigableMap we use methods to
return the key value pair like navMap.put(1, "January"); whereas in NavigableSet we use methods to
return values.ConcurrentSkipListMap is the one of the class which implements NavigableMap. Lets
have a look at the example.

Description of program:

The following program helps you in inserting, removing and retrieving the data from the NavigableMap. It uses theput() method to add the
element. If you want to retrieve the data at first and last position from the NavigableMap, you use the firstEntry() and lastEntry() methods.
The descendingMap() method represents all data to the NavigableMap in descending order. 

You can retrieve the nearest less than or equal to the given number and the greatest key strictly less than the given
number floorEntry() and lowerEntry() methods. And you retrieve a key-value associated with the least key strictly greater than the given key,
you use the higherEntry() method. The pollFirstEntry() method removes the first data from the NavigableMap and pollLastEntry() method
also removes the data at the last position from the NavigableMap.

Here is the code of program:


import java.util.*;
import java.util.concurrent.*;

public class NavigableMapExample{
  public static void main(String[] args) {
  System.out.println("Navigable Map Example!\n");
  NavigableMap <Integer, String>navMap = new 
   ConcurrentSkipListMap<Integer, String>();
  navMap.put(1, "January");
  navMap.put(2, "February");
  navMap.put(3, "March");
  navMap.put(4, "April");
  navMap.put(5, "May");
  navMap.put(6, "June");
  navMap.put(7, "July");
  navMap.put(8, "August");
  navMap.put(9, "September");
  navMap.put(10, "October");
  navMap.put(11, "November");
  navMap.put(12, "December");
  //Displaying all data
  System.out.println("Data in the navigable map: " + 
    navMap.descendingMap()+"\n");
  //Retrieving first data
  System.out.print("First data: " + navMap.firstEntry()+"\n");
  //Retrieving last data
  System.out.print("Last data: " + navMap.lastEntry()+"\n\n");
  //Retrieving the nreatest less than or equal to the given key
  System.out.print("Nearest less than or equal to the given key: " 
  + navMap.floorEntry(5)+"\n");
  //Retrieving the greatest key strictly less than the given key
  System.out.println("Retrieving the greatest key strictly less than 
   the given key: " + navMap.lowerEntry(3));
  //Retrieving a key-value associated with the least key 
  strictly greater than the given key
  System.out.println("Retriving data from navigable map greter than 
   the given key: " + navMap.higherEntry(5)+"\n");
  //Removing first
  System.out.println("Removing First: " + navMap.pollFirstEntry());
  //Removing last
  System.out.println("Removing Last: " + navMap.pollLastEntry()+"\n");
  //Displaying all data
  System.out.println("Now data: " + navMap.descendingMap());
  }
}
Download this example.
Output of program:

C:\vinod\collection>javac NavigableMapExample.java

C:\vinod\collection>java NavigableMapExample
Navigable Map Example!

Data in the navigable map: {12=December, 11=November,


10=October, 9=September, 8
=August, 7=July, 6=June, 5=May, 4=April, 3=March,
2=February, 1=January}

First data: 1=January


Last data: 12=December

Nearest less than or equal to the given key: 5=May


Retrieving the greatest key strictly less than the given key:
2=February
Retriving data from navigable map greter than the given key:
6=June

Removing First: 1=January


Removing Last: 12=December

Now data: {11=November, 10=October, 9=September,


8=August, 7=July, 6=June, 5=May
, 4=April, 3=March, 2=February}

C:\vinod\collection>

Navigable Set Example


       
In the example below we have used NavigableSet method to sort the elements in ascending order, descending order, also to retrieve the element
which is immediately greater than or equal to 35 etc. With the help of NavigableSet methods its just a method call to get the result. It is used to
return the closest matches of elements for the given elements in the collection.  
Description of program:

Inserting the data in the NavigableSet by the add() method. The NavigableSet provides the facility to getting the data in both orders: ascending
and descending orders. The descendingSet() method returns the data from the NavigableSet in descending order. If you want to get the data in
ascending order must be used an iterator. An iterator stores the data as a index and the hasNext() method returns 'true' until, the next() method
returns the element in ascending order. 

Here, you remove the element from the NavigableSet at first and last position, you use the pollFirst() and pollLast() methods. Sometimes, you
want to get the less and greater than or equal to the given element by using the floor() and ceiling() methods. For getting the all elements of the
NavigableSet that is greater than or equal to the given element by the tailSet() method and less than or equal to the given element of the
NavigableSet by theheadSet() method. 

Here is the code of program:


import java.util.*;
import java.util.concurrent.*;

public class NavigableSetExample{
  public static void main(String[] args) {
  System.out.println("Navigable set Example!\n");
  NavigableSet <Integer>nSet = new ConcurrentSkipListSet<Integer>();
  nSet.add(10);
  nSet.add(20);
  nSet.add(50);
  nSet.add(30);
  nSet.add(100);
  nSet.add(80);
  // Returns an iterator over the elements in navigable set,
    in ascending order.
  Iterator iterator = nSet.iterator();
  System.out.print("Ascending order navigable set: ");
  //Ascending order list
  while (iterator.hasNext()){
  System.out.print(iterator.next() + " ");
  }
  System.out.println();
  //Descending order list
  System.out.println("Descending order navigable set: " + 
   nSet.descendingSet() + "\n");
  //Greater than or equal to the given element
  System.out.println("Least element in Navigable set greater than 
   or equal to 35: " + nSet.ceiling(35));
  //Less than or equal to the given element
  System.out.println("Greatest element in Navigable set less than 
   or equal to 35: " + nSet.floor(35) + "\n");
  //Viewing the portion of navigable set whose elements are 
  strictly less than the given element
  System.out.println("Navigable set whose elements are strictly 
   less than '40': " + nSet.headSet(40));
  //Viewing the portion of navigable set whose elements are 
  greater than or equal to the given element
  System.out.println("Navigable set whose elements are greater 
  than or equal to '40': " + nSet.tailSet(40) + "\n");
  //Removing first element from navigable set
  System.out.println("Remove element: "+nSet.pollFirst());
  //After removing the first element, now get navigable set
  System.out.println("Now navigable set: " + nSet.descendingSet() + "\n");
  //Removing last element from navigable set
  System.out.println("Remove element: " + nSet.pollLast());
  //After removing the last element, now get navigable set
  System.out.println("Now navigable set: " + nSet.descendingSet());
  }
}
 Download this Example.
Output of this program

C:\vinod\collection>javac
NavigableSetExample.java

C:\vinod\collection>java NavigableSetExample
Navigable set Example!

Ascending order navigable set: 10 20 30 50 80


100
Descending order navigable set: [100, 80, 50, 30,
20, 10]

Least element in Navigable set greater than or


equal to 35: 50
Greatest element in Navigable set less than or
equal to 35: 30

Navigable set whose elements are strictly less than


'40': [10, 20, 30]
Navigable set whose elements are greater than or
equal to '40': [50, 80, 100]

Remove element: 10
Now navigable set: [100, 80, 50, 30, 20]

Remove element: 100


Now navigable set: [80, 50, 30, 20]

C:\vinod\collection>

HashSet Example
       
In this section we are discussing HashSet with example code that shows the methods to add, remove and iterate the values of
collection. A HashSet is a collection set that neither allows duplicate elements nor order or position its elements.

Description of program:

In the following code segment we are performing various operations on HashSet collection. We have explained the steps to add, remove, and test
the elements of the collection. Keys are used to put and get values. We can also execute this code on a Vector by changing the HashSet
declaration and constructor to a Vector as it supports the collection interface.  

To insert an element in the HashSet collection add() method is used. The size() method helps you in getting the size of the collection. If you want
to delete any element, use the remove() method which takes index as parameter. In order to remove all data from the HashSet use clear() method.
When the HashSet is empty, our program checks for it and displays a message "Collection is empty". If the collection is not empty then program
displays the size of HashSet.

Here is the code of program:


import java.util.*;

public class CollectionTest {
  public static void main(String [] args) { 
  System.out.println( "Collection Example!\n" ); 
  int size;
  // Create a collection  
  HashSet <String>collection = new HashSet <String>();
  String str1 = "Yellow", str2 = "White", str3 = "Green", str4 = "Blue";  
  Iterator iterator;
  //Adding data in the collection
  collection.add(str1);  
  collection.add(str2); 
  collection.add(str3); 
  collection.add(str4);
  System.out.print("Collection data: ");  
  //Create a iterator
  iterator = collection.iterator(); 
  while (iterator.hasNext()){
  System.out.print(iterator.next() + " ");  
  }
  System.out.println();
  // Get size of a collection
  size = collection.size();
  if (collection.isEmpty()){
  System.out.println("Collection is empty");
  }
  else{
  System.out.println( "Collection size: " + size);
  }
  System.out.println();
  // Remove specific data  
  collection.remove(str2);
  System.out.println("After removing [" + str2 + "]\n");
  System.out.print("Now collection data: ");
  iterator = collection.iterator(); 
  while (iterator.hasNext()){
  System.out.print(iterator.next() + " ");  
  }
  System.out.println();
  size = collection.size();
  System.out.println("Collection size: " + size + "\n");
  //Collection empty
  collection.clear();
  size = collection.size();
  if (collection.isEmpty()){
  System.out.println("Collection is empty");
  }
  else{
  System.out.println( "Collection size: " + size);
  }
  }
}
Download this example.
Output of this program:

C:\vinod\collection>javac
CollectionTest.java

C:\vinod\collection>java
CollectionTest
Collection Example!

Collection data: Blue White


Green Yellow
Collection size: 4

After removing [White]

Now collection data: Blue


Green Yellow
Collection size: 3

Collection is empty

C:\vinod\collection>

Linked List Example


       
This section discusses an example to demonstrate the various methods of List interface. We are using
two classes ArrayList and LinkedList in the example code. The code below is similar to the previous
example, but it performs many List operations. Lets discuss the example code.
Description of program:

This program helps you in storing the large amount of data as a collection. The LinkedList is a part of collection that constructs a list containing
the elements of the specified collection. Iterator methods returns the values in the order in which they are stored.

If you want to insert the data in the linkedList then use add() method. The hasNext() method returns true if the iterator contains more elements
and the next() method returns the next element in the iteration. To insert and remove the data at first, last and specified position in the linkedList,
you use the addFirst(), addLast(), add(), removeFirst(), removeLast() and remove() methods. To retrieve the element with respect to a
specified position use the getFirst(), getLast() and get() methods.  

Here is the code of program:


import java.util.*;

public class LinkedListExample{
  public static void main(String[] args) {
  System.out.println("Linked List Example!");
  LinkedList <Integer>list = new LinkedList<Integer>();
  int num1 = 11, num2 = 22, num3 = 33, num4 = 44;
  int size;
  Iterator iterator;
  //Adding data in the list
  list.add(num1);
  list.add(num2);
  list.add(num3);
  list.add(num4);
  size = list.size();
  System.out.print( "Linked list data: ");  
  //Create a iterator
  iterator = list.iterator(); 
  while (iterator.hasNext()){
  System.out.print(iterator.next()+" ");  
  }
  System.out.println();
  //Check list empty or not
  if (list.isEmpty()){
  System.out.println("Linked list is empty");
  }
  else{
  System.out.println( "Linked list size: " + size);
  }
  System.out.println("Adding data at 1st location: 55");
  //Adding first
  list.addFirst(55);
  System.out.print("Now the list contain: ");
  iterator = list.iterator();
  while (iterator.hasNext()){
  System.out.print(iterator.next()+" ");  
  }
  System.out.println();
  System.out.println("Now the size of list: " + list.size());
  System.out.println("Adding data at last location: 66");
  //Adding last or append
  list.addLast(66);
  System.out.print("Now the list contain: ");
  iterator = list.iterator();
  while (iterator.hasNext()){
  System.out.print(iterator.next()+" ");  
  }
  System.out.println();
  System.out.println("Now the size of list: " + list.size());
  System.out.println("Adding data at 3rd location: 55");
  //Adding data at 3rd position
  list.add(2,99);
  System.out.print("Now the list contain: ");
  iterator = list.iterator();
  while (iterator.hasNext()){
  System.out.print(iterator.next()+" ");  
  }
  System.out.println();
  System.out.println("Now the size of list: " + list.size());
  //Retrieve first data
  System.out.println("First data: " + list.getFirst());
  //Retrieve lst data
  System.out.println("Last data: " + list.getLast());
  //Retrieve specific data
  System.out.println("Data at 4th position: " + list.get(3));
  //Remove first
  int first = list.removeFirst();
  System.out.println("Data removed from 1st location: " + first);
  System.out.print("Now the list contain: ");
  iterator = list.iterator();
  //After removing data
  while (iterator.hasNext()){
  System.out.print(iterator.next()+" ");  
  }
  System.out.println();
  System.out.println("Now the size of list: " + list.size());
  //Remove last
  int last = list.removeLast();
  System.out.println("Data removed from last location: " + last);
  System.out.print("Now the list contain: ");
  iterator = list.iterator();
  //After removing data
  while (iterator.hasNext()){
  System.out.print(iterator.next()+" ");  
  }
  System.out.println();
  System.out.println("Now the size of list: " + list.size());
  //Remove 2nd data
  int second = list.remove(1);
  System.out.println("Data removed from 2nd location: " + second);
  System.out.print("Now the list contain: ");
  iterator = list.iterator();
  //After removing data
  while (iterator.hasNext()){
  System.out.print(iterator.next()+" ");  
  }
  System.out.println();
  System.out.println("Now the size of list: " + list.size());
  //Remove all
  list.clear();
  if (list.isEmpty()){
  System.out.println("Linked list is empty");
  }
  else{
  System.out.println( "Linked list size: " + size);
  }
  }
}
Download this example.
Output of program:

C:\vinod\collection>javac
LinkedListExample.java

C:\vinod\collection>java
LinkedListExample
Linked List Example!
Linked list data: 11 22 33 44
Linked list size: 4
Adding data at 1st location: 55
Now the list contain: 55 11 22
33 44
Now the size of list: 5
Adding data at last location: 66
Now the list contain: 55 11 22
33 44 66
Now the size of list: 6
Adding data at 3rd location: 55
Now the list contain: 55 11 99
22 33 44 66
Now the size of list: 7
First data: 55
Last data: 66
Data at 4th position: 22
Data removed from 1st location:
55
Now the list contain: 11 99 22
33 44 66
Now the size of list: 6
Data removed from last location:
66
Now the list contain: 11 99 22
33 44
Now the size of list: 5
Data removed from 2nd
location: 99
Now the list contain: 11 22 33
44
Now the size of list: 4
Linked list is empty

C:\vinod\collection>

Tree Map Example


       
In the following example, we have used the TreeMap method, which stores its elements in a tree and orders its elements based on their values.
Here in the example we have used the key of the element to show the values of the element. To retrieve the keys and values
use keySet() and values() method respectively. 

This program shows the data elements left after removing the particular element by specifying its key. Using the Iterator interface methods, we
can traverse a collection from start to finish and safely remove elements from the underlying Collection.

 Here is the code of program:


import java.util.*;

public class TreeMapExample{

public static void main(String[] args) {

System.out.println("Tree Map Example!\n");

TreeMap <Integer, String>tMap = new TreeMap<Integer, String>();

//Addding data to a tree map

tMap.put(1, "Sunday");

tMap.put(2, "Monday");

tMap.put(3, "Tuesday");

tMap.put(4, "Wednesday");
tMap.put(5, "Thursday");

tMap.put(6, "Friday");

tMap.put(7, "Saturday");

//Rerieving all keys

System.out.println("Keys of tree map: " + tMap.keySet());

//Rerieving all values

System.out.println("Values of tree map: " + tMap.values());

//Rerieving the value from key with key number 5

System.out.println("Key: 5 value: " + tMap.get(5)+ "\n");

//Rerieving the First key and its value

System.out.println("First key: " + tMap.firstKey() + " Value: "

+ tMap.get(tMap.firstKey()) + "\n");

//Rerieving the Last key and value

System.out.println("Last key: " + tMap.lastKey() + " Value: "

+ tMap.get(tMap.lastKey()) + "\n");

//Removing the first key and value

System.out.println("Removing first data: "

+ tMap.remove(tMap.firstKey()));

System.out.println("Now the tree map Keys: " + tMap.keySet());

System.out.println("Now the tree map contain: "

+ tMap.values() + "\n");

//Removing the last key and value

System.out.println("Removing last data: "

+ tMap.remove(tMap.lastKey()));

System.out.println("Now the tree map Keys: " + tMap.keySet());

System.out.println("Now the tree map contain: " + tMap.values());

Download this example.


Output of this program:

C:\vinod\collection>javac TreeMapExample.java

C:\vinod\collection>java TreeMapExample
Tree Map Example!

Keys of tree map: [1, 2, 3, 4, 5, 6, 7]


Values of tree map: [Sunday, Monday, Tuesday, Wednesday,
Thursday, Friday, Saturday]
Key: 5 value: Thursday

First key: 1 Value: Sunday

Last key: 7 Value: Saturday

Removing first data: Sunday


Now the tree map Keys: [2, 3, 4, 5, 6, 7]
Now the tree map contain: [Monday, Tuesday, Wednesday,
Thursday, Friday, Saturday]

Removing last data: Saturday


Now the tree map Keys: [2, 3, 4, 5, 6]
Now the tree map contain: [Monday, Tuesday, Wednesday,
Thursday, Friday]

C:\vinod\collection>

Tree Set Example


       
In the following example, we have used the TreeSet collection, which is similar to TreeMap that stores its elements in a tree and maintain order
of its elements based on their values. To get the size of TreeSet collection size()method is used. Our TreeSet collection contains 4 elements and
the size of the TreeSet can be determine by calling size() method. 

Similarly, we have used first() and last() to retrieve first and last element present in the TreeSet. Program also shows the method to remove the
element and then display the remaining elements. To remove all data from the TreeSet, use the clear() method. To determine whether TreeSet is
empty or not use isEmpty() method. If the TreeSet is empty, it displays the message "Tree set is empty." otherwise it displays the size of TreeSet.

 Here is the code of program:


import java.util.*;

public class TreeSetExample{
  public static void main(String[] args) {
  System.out.println("Tree Set Example!\n");
  TreeSet <Integer>tree = new TreeSet<Integer>();
  tree.add(12);
  tree.add(23);
  tree.add(34);
  tree.add(45);
  Iterator iterator;
  iterator = tree.iterator();
  System.out.print("Tree set data: ");
  //Displaying the Tree set data
  while (iterator.hasNext()){
  System.out.print(iterator.next() + " ");
  }
  System.out.println();
  //Check impty or not
  if (tree.isEmpty()){
  System.out.print("Tree Set is empty.");
  }
  else{
  System.out.println("Tree Set size: " + tree.size());
  }
  //Retrieve first data from tree set
  System.out.println("First data: " + tree.first());
  //Retrieve last data from tree set
  System.out.println("Last data: " + tree.last());
  if (tree.remove(30)){
  System.out.println("Data is removed from tree set");
  }
  else{
  System.out.println("Data doesn't exist!");
  }
  System.out.print("Now the tree set contain: ");
  iterator = tree.iterator();
  //Displaying the Tree set data
  while (iterator.hasNext()){
  System.out.print(iterator.next() + " ");
  }
  System.out.println();
  System.out.println("Now the size of tree set: " + tree.size());
  //Remove all
  tree.clear();
  if (tree.isEmpty()){
  System.out.print("Tree Set is empty.");
  }
  else{
  System.out.println("Tree Set size: " + tree.size());
  }
  }
}
Download this example.
Output of this program:

C:\vinod\collection>javac
TreeSetExample.java

C:\vinod\collection>java
TreeSetExample
Tree Set Example!

Tree set data: 12 23 34 45


Tree Set size: 4
First data: 12
Last data: 45
Data doesn't exist!
Now the tree set contain: 12 23
34 45
Now the size of tree set: 4
Tree Set is empty.

C:\vinod\collection>
Java SE 7 Features and Enhancements
Java Platform, Standard Edition 7 is a major feature release. This document includes information on features and enhancements in Java SE 7 and in JDK 7,
Oracle's implementation of Java SE 7. 

Contents
 Highlights of Technology Changes in Java SE 7
 Important RFEs Addressed in Java SE 7
 Important RFEs Addressed in JDK 7
 Known Issues

Highlights of Technology Changes in Java SE 7

The following list contains links to the the enhancements pages in the Java SE 7 guides documentation.
Choose a technology for further information.
 
 Swing
 IO and New IO
 Networking
 Security
 Concurrency Utilities
 Rich Internet Applications (RIA)/Deployment
 Requesting and Customizing Applet Decoration in Dragg able Applets
 Embedding JNLP File in Applet Tag
 Deploying without Codebase
 Handling Applet Initialization Status with Event Handlers
 Java 2D
 Java XML - JAXP, JAXB, and JAX-WS
 Internationalization
 java.lang Package
 Multithreaded Custom Class Loaders in Java SE 7
 Java Programming Language
 Binary Literals
 Strings in switch Statements
 The try-with-resources Statement
 Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking
 Underscores in Numeric Literals
 Type Inference for Generic Instance Creation
 Improved Compiler Warnings and Errors When Using Non-Reifiable Formal Parameters with Varargs
Methods
 Java Virtual Machine (JVM)
 Java Virtual Machine Support for Non-Java Languages
 Garbage-First Collector
 Java HotSpot Virtual Machine Performance Enhancements
 JDBC
Java 8 Features with Examples
APRIL 6, 2018 BY PANKAJ 70 COMMENTS

Java 8 was released in 18th March 2014, so it’s high time to look into Java 8 Features. In this tutorial,
we will look into Java 8 features with examples.

Java 8 Features

Some of the important Java 8 features are;

1. forEach() method in Iterable interface

2. default and static methods in Interfaces

3. Functional Interfaces and Lambda Expressions

4. Java Stream API for Bulk Data Operations on Collections

5. Java Time API

6. Collection API improvements

7. Concurrency API improvements

8. Java IO improvements

9. Miscellaneous Core API improvements


Let’s have a brief look on these Java 8 features. I will provide some code snippets for better
understanding, so if you want to run programs in Java 8, you will have to setup Java 8 environment by
following steps.

 Download JDK8 and install it. Installation is simple like other java versions. JDK installation is
required to write, compile and run the program in Java.

 Download latest Eclipse IDE, it provides support for java 8 now. Make sure your projects build
path is using Java 8 library.

Learning Java? Nothing better than a video course trusted by over 1,70,000 students (yes, that

many students). Follow this link to get heavy discount on the course.

 forEach() method in Iterable interface


Whenever we need to traverse through a Collection, we need to create an Iteratorwhose whole
purpose is to iterate over and then we have business logic in a loop for each of the elements in the
Collection. We might get ConcurrentModificationException if iterator is not used properly.

Java 8 has introduced forEach method in java.lang.Iterable interface so that while


writing code we focus on business logic only. forEach method
takes java.util.function.Consumer object as argument, so it helps in having our
business logic at a separate location that we can reuse. Let’s see forEach usage with simple
example.

package com.journaldev.java8.foreach;

import java.util.ArrayList;

import java.util.Iterator;

import java.util.List;

import java.util.function.Consumer;

import java.lang.Integer;
public class Java8ForEachExample {

public static void main(String[] args) {

//creating sample Collection

List<Integer> myList = new ArrayList<Integer>();

for(int i=0; i<10; i++) myList.add(i);

//traversing using Iterator

Iterator<Integer> it = myList.iterator();

while(it.hasNext()){

Integer i = it.next();

System.out.println("Iterator Value::"+i);

//traversing through forEach method of Iterable with anonymous


class

myList.forEach(new Consumer<Integer>() {

public void accept(Integer t) {

System.out.println("forEach anonymous class


Value::"+t);

});

//traversing with Consumer interface implementation


MyConsumer action = new MyConsumer();

myList.forEach(action);

//Consumer implementation that can be reused

class MyConsumer implements Consumer<Integer>{

public void accept(Integer t) {

System.out.println("Consumer impl Value::"+t);

The number of lines might increase but forEach method helps in having the logic for iteration and
business logic at separate place resulting in higher separation of concern and cleaner code.

 default and static methods in Interfaces


If you read forEach method details carefully, you will notice that it’s defined in Iterable interface
but we know that interfaces can’t have method body. From Java 8, interfaces are enhanced to have
method with implementation. We can use default and statickeyword to create interfaces
with method implementation. forEach method implementation in Iterable interface is:

default void forEach(Consumer<? super T> action) {

Objects.requireNonNull(action);

for (T t : this) {
action.accept(t);

We know that Java doesn’t provide multiple inheritance in Classes because it leads to Diamond


Problem. So how it will be handled with interfaces now, since interfaces are now similar to
abstract classes. The solution is that compiler will throw exception in this scenario and we will
have to provide implementation logic in the class implementing the interfaces.

package com.journaldev.java8.defaultmethod;

@FunctionalInterface

public interface Interface1 {

void method1(String str);

default void log(String str){

System.out.println("I1 logging::"+str);

static void print(String str){

System.out.println("Printing "+str);

//trying to override Object method gives compile time error as

//"A default method cannot override a method from java.lang.Object"

// default String toString(){


// return "i1";

// }

package com.journaldev.java8.defaultmethod;

@FunctionalInterface

public interface Interface2 {

void method2();

default void log(String str){

System.out.println("I2 logging::"+str);

Notice that both the interfaces have a common method log() with implementation logic.

package com.journaldev.java8.defaultmethod;

public class MyClass implements Interface1, Interface2 {

@Override

public void method2() {


}

@Override

public void method1(String str) {

//MyClass won't compile without having it's own log() implementation

@Override

public void log(String str){

System.out.println("MyClass logging::"+str);

Interface1.print("abc");

As you can see that Interface1 has static method implementation that is used


in MyClass.log() method implementation. Java 8 uses default and static methods heavily
in Collection API and default methods are added so that our code remains backward compatible.

If any class in the hierarchy has a method with same signature, then default methods become
irrelevant. Since any class implementing an interface already has Object as superclass, if we have
equals(), hashCode() default methods in interface, it will become irrelevant. Thats why for better
clarity, interfaces are not allowed to have Object class default methods.

For complete details of interface changes in Java 8, please read Java 8 interface changes.

 Functional Interfaces and Lambda Expressions


If you notice above interfaces code, you will notice @FunctionalInterface annotation. Functional
interfaces are new concept introduced in Java 8. An interface with exactly one abstract method
becomes Functional Interface. We don’t need to use @FunctionalInterface annotation to mark an
interface as Functional Interface. @FunctionalInterface annotation is a facility to avoid accidental
addition of abstract methods in the functional interfaces. You can think of it like @Override
annotation and it’s best practice to use it. java.lang.Runnable with single abstract method
run() is a great example of functional interface.

One of the major benefits of functional interface is the possibility to use lambda expressions to
instantiate them. We can instantiate an interface with anonymous classbut the code looks bulky.

Runnable r = new Runnable(){

@Override

public void run() {

System.out.println("My Runnable");

}};

Since functional interfaces have only one method, lambda expressions can easily provide the
method implementation. We just need to provide method arguments and business logic. For
example, we can write above implementation using lambda expression as:

Runnable r1 = () -> {

System.out.println("My Runnable");

};

If you have single statement in method implementation, we don’t need curly braces also. For
example above Interface1 anonymous class can be instantiated using lambda as follows:

Interface1 i1 = (s) -> System.out.println(s);

i1.method1("abc");

So lambda expressions are means to create anonymous classes of functional interfaces easily.
There are no runtime benefits of using lambda expressions, so I will use it cautiously because I
don’t mind writing few extra lines of code.
A new package java.util.function has been added with bunch of functional interfaces to
provide target types for lambda expressions and method references. Lambda expressions are a
huge topic, I will write a separate article on that in future.

You can read complete tutorial at Java 8 Lambda Expressions Tutorial.

 Java Stream API for Bulk Data Operations on Collections


A new java.util.stream has been added in Java 8 to perform filter/map/reduce like
operations with the collection. Stream API will allow sequential as well as parallel execution. This
is one of the best feature for me because I work a lot with Collections and usually with Big Data,
we need to filter out them based on some conditions.

Collection interface has been extended with stream() and parallelStream() default methods to get


the Stream for sequential and parallel execution. Let’s see their usage with simple example.

package com.journaldev.java8.stream;

import java.util.ArrayList;

import java.util.List;

import java.util.stream.Stream;

public class StreamExample {

public static void main(String[] args) {

List<Integer> myList = new ArrayList<>();

for(int i=0; i<100; i++) myList.add(i);

//sequential stream

Stream<Integer> sequentialStream = myList.stream();


//parallel stream

Stream<Integer> parallelStream = myList.parallelStream();

//using lambda with Stream API, filter example

Stream<Integer> highNums = parallelStream.filter(p -> p > 90);

//using lambda in forEach

highNums.forEach(p -> System.out.println("High Nums


parallel="+p));

Stream<Integer> highNumsSeq = sequentialStream.filter(p -> p >


90);

highNumsSeq.forEach(p -> System.out.println("High Nums


sequential="+p));

If you will run above example code, you will get output like this:

High Nums parallel=91

High Nums parallel=96

High Nums parallel=93

High Nums parallel=98

High Nums parallel=94

High Nums parallel=95

High Nums parallel=97


High Nums parallel=92

High Nums parallel=99

High Nums sequential=91

High Nums sequential=92

High Nums sequential=93

High Nums sequential=94

High Nums sequential=95

High Nums sequential=96

High Nums sequential=97

High Nums sequential=98

High Nums sequential=99

Notice that parallel processing values are not in order, so parallel processing will be very helpful
while working with huge collections.
Covering everything about Stream API is not possible in this post, you can read everything about
Stream API at Java 8 Stream API Example Tutorial.

 Java Time API


It has always been hard to work with Date, Time and Time Zones in java. There was no standard
approach or API in java for date and time in Java. One of the nice addition in Java 8 is
the java.time package that will streamline the process of working with time in java.

Just by looking at Java Time API packages, I can sense that it will be very easy to use. It has some
sub-packages java.time.format that provides classes to print and parse dates and times
and java.time.zone provides support for time-zones and their rules.

The new Time API prefers enums over integer constants for months and days of the week. One of
the useful class is DateTimeFormatter for converting datetime objects to strings.

For complete tutorial, head over to Java Date Time API Example Tutorial.

 Collection API improvements


We have already seen forEach() method and Stream API for collections. Some new methods added
in Collection API are:
 Iterator default method forEachRemaining(Consumer action) to perform the
given action for each remaining element until all elements have been processed or the action
throws an exception.

 Collection default method removeIf(Predicate filter) to remove all of the


elements of this collection that satisfy the given predicate.

 Collection spliterator() method returning Spliterator instance that can be used to


traverse elements sequentially or parallel.

 Map replaceAll(), compute(), merge() methods.

 Performance Improvement for HashMap class with Key Collisions

 Concurrency API improvements


Some important concurrent API enhancements are:

 ConcurrentHashMap compute(), forEach(), forEachEntry(), forEachKey(),


forEachValue(), merge(), reduce() and search() methods.

 CompletableFuture that may be explicitly completed (setting its value and status).

 Executors newWorkStealingPool() method to create a work-stealing thread pool


using all available processors as its target parallelism level.

 Java IO improvements
Some IO improvements known to me are:

 Files.list(Path dir) that returns a lazily populated Stream, the elements of which


are the entries in the directory.

 Files.lines(Path path) that reads all lines from a file as a Stream.

 Files.find() that returns a Stream that is lazily populated with Path by searching for
files in a file tree rooted at a given starting file.

 BufferedReader.lines() that return a Stream, the elements of which are lines read


from this BufferedReader.
 Miscellaneous Core API improvements
Some misc API improvements that might come handy are:

 ThreadLocal static method withInitial(Supplier supplier) to create instance easily.


 Comparator interface has been extended with a lot of default and static methods for natural
ordering, reverse order etc.
 min(), max() and sum() methods in Integer, Long and Double wrapper classes.
 logicalAnd(), logicalOr() and logicalXor() methods in Boolean class.
 ZipFile.stream() method to get an ordered Stream over the ZIP file entries. Entries appear in
the Stream in the order they appear in the central directory of the ZIP file.
 Several utility methods in Math class.
 jjs command is added to invoke Nashorn Engine.
 jdeps command is added to analyze class files
 JDBC-ODBC Bridge has been removed.
 PermGen memory space has been removed
That’s all for Java 8 features with example programs. If I have missed some important features of Java
8, please let me know through comments.

TWITTERFACEBOOKLINKEDINEMAIL

 PREVIOUS  NEXT 
Java Lock Example – ReentrantLock Google Guice Dependency Injection Example Tutorial

About Pankaj
If you have come this far, it means that you liked what you are reading. Why not reach little more and
connect with me directly on Google Plus, Facebook or Twitter. I would love to hear your thoughts
and opinions on my articles directly.

Recently I started creating video tutorials too, so do check out my videos on Youtube.

FILED UNDER: JAVA

Comments

1. Sudhakar says
JULY 8, 2018 AT 10:17 PM

Thanks for great tutorial

Reply

2. Ravi Gupta says

JUNE 16, 2018 AT 11:36 PM

Jcmd for thread dump in java8

Reply

3. vellai varanan says
MAY 24, 2018 AT 9:08 PM

very good to read.good analysis.

thanks m pankaj

Reply

4. Meghala Devi says

MAY 8, 2018 AT 3:13 AM

Thanks a lot Pankaj for the wonderful article.

Reply
5. Md. Ahsan Kabir says

MAY 7, 2018 AT 11:15 PM

Among them, I think stream, time and lambda expression API are the best features. Thanks to #pankaj for this

awesome tutorial.

Reply

6. BALAGURIAH says

MAY 2, 2018 AT 8:56 PM

okk but i think new version


Reply

 Pankaj says

JUNE 7, 2018 AT 6:12 AM

Don’t we all, Balaguriah? Don’t we all….

Reply

7. Ashish Balani says

APRIL 25, 2018 AT 6:43 AM


Also, the HashMaps now use a Tree instead of a LinkedList when number of linked nodes cross a threshold. The

default TREEIFY threshold is 8, and default UNTREEIFY threshold is 6. This means, when number of nodes cross 8

a tree structure would be formed and if you remove nodes the tree structure would change after it reaches 6.

Reply

8. Rumpee says

APRIL 16, 2018 AT 5:53 AM

Static methods in Functional Interface .


@FunctionalInterface

interface MyFunctionalInterface

public int addMethod(int a, int b);

static void method1()

System.out.println(“Static method1 implementation”);

static void method2()

{
System.out.println(“Static method2 implementation”);

public class StaticMethodDemo implements MyFunctionalInterface{

/**

* By default static methods are not available to implementation class .

* So no overriding .

* */

static void method2()

{
System.out.println(“Static method2 implementation”);

public void method1()

System.out.println(“Instance method1 implementation”);

private static void method3()

System.out.println(“Static method3 implementation”);

}
public static void main(String[] args) {

MyFunctionalInterface.method2();

@Override

public int addMethod(int a, int b) {

// TODO Auto-generated method stub

return 0;

Few points on Static Methods in Interface with Java 1.8


General utility methods are to be added as static methods in interface which are not related to Object State

The methods can be called with Interface name not implementation object reference or implementation class name

Not available by default to implementation class

Overriding not applicable for interface static method as it is not available by default to implementation class

Main method can be declared inside interface .

Can execute main method inside interface .

Reply

9. Mridula says

MARCH 31, 2018 AT 12:20 AM


Here are some features of Java 8:

1. Implementation of Lambda expressions.

2. Date and Time API.

3. A lightweight, high performance implementation of JavaScript engine is integrated to JDK.

4. Improved Security

Reply

10. Jyoti Namdeo says

MARCH 15, 2018 AT 1:04 PM

It was a great help.


Reply

11. Ahmad Sayeed says

MARCH 11, 2018 AT 1:10 AM

Thank you for sharing . Please keep it up.

Reply

12. Abdulaziz says

JANUARY 4, 2018 AT 12:44 PM

Nice and easy-to-follow article about main java 8 features. Thank you.
Reply

13. kalpesh soni says

JANUARY 4, 2018 AT 9:33 AM

Rest of the stuff was REALLY useful but

lambda was the lamest

people wrote entire books about why lambda expressions are elegant and useful

and all you can say is

I dont mind extra code? really?


Reply

 Pankaj says

JANUARY 4, 2018 AT 10:47 AM

Could you show me an example where lambda expressions brings real benefits such as better performance (like

StringBuilder brings over StringBuffer)? Ultimately lambda expression reduces the code size and if not used wisely, it

could get messy. That’s why I mentioned that if you are not too familiar with it, better go with the basics even if it

cause few extra lines of code. I use it in my code but not all the time, I am still not comfortable with “method

reference” (::) and still write System.out.println rather than System.out::println.


Reply

 Rahul kumar says

JANUARY 22, 2018 AT 2:45 AM

Lambda expression allowed us functional programming rather than reduces the code.

“System.out.println vs System.out::println.”

Reply

14. Mithila says

DECEMBER 30, 2017 AT 1:00 AM


Thanks for the consolidate information and even links for elaborations 🙂

Reply

15. Thirupathi says

NOVEMBER 21, 2017 AT 3:35 AM

wonderful information , And easy to understand

Reply

16. hashem yousefi says

OCTOBER 14, 2017 AT 1:25 AM


tnx. very nice

Reply

17. Gaurav Jain says

AUGUST 14, 2017 AT 1:24 PM

Thanxxxxxxxxxxx Pankaj ,

You saved my day , All information at one place … Thnxxx again 🙂

Reply

18. Ajeet Patel says


JUNE 21, 2017 AT 5:22 AM

Thanks a lot Pankaj. A very concise and self explanatory info and that too at a one place. 🙂

Reply

 Pankaj says

JULY 17, 2017 AT 11:24 AM

You are welcome Ajeet, appreciate the kind words.

Reply

19. Nitin says
MAY 15, 2017 AT 10:14 AM

You can also discuss about method reference in this tutorial. Method reference is also a very important feature in Java

Reply

 Pankaj says

JULY 17, 2017 AT 12:24 PM

It’s good to know but it’s just to reduce number of lines of code.

Reply
20. Tomasz Krzysztof says

MAY 7, 2017 AT 1:30 AM

Thank you!

Reply

21. Valentino says

APRIL 27, 2017 AT 10:24 PM

Pankaj, I guess when you say “Make sure your projects build patch is using Java 8 library.” you mean build path,

right?
Reply

 Pankaj says

APRIL 27, 2017 AT 11:16 PM

Yes, build path. corrected it.

Reply

22. Rama says

APRIL 7, 2017 AT 1:56 PM

In forEach example, MyConsumer should be static inner class not just inner class if we want to use that in main().
Reply

23. Arvind says

APRIL 6, 2017 AT 2:58 PM

You can override default interface. It wont complain.

Reply

24. Harry S. Green says

MARCH 23, 2017 AT 1:37 PM

Very helpful. I’m very grateful to see such topics discussed here.
Reply

25. Krishnan K says

MARCH 2, 2017 AT 5:24 AM

Good Article, Thanks a lot…

Reply

26. Narendra b says

MARCH 1, 2017 AT 1:34 AM

Simply superb
Reply

27. Raj Rusia says

FEBRUARY 27, 2017 AT 8:58 PM

It’s very useful to know overview of new features of Java 8 in less time.

Reply

28. jdk1.7 says

FEBRUARY 3, 2017 AT 7:17 AM

Is it me or these new features are turning the language into unreadable mess
Reply

29. Mayur Patel says

DECEMBER 16, 2016 AT 10:47 PM

Hello Sir,

Could you please justify the statement “Performance Improvement for HashMap class with Key Collisions”.?

How they have improved the HashMap class with Key Collisions?

Reply

 Dileep says
DECEMBER 29, 2016 AT 6:08 AM

In Java 8 we have below changes,

in case of collision till Java 7 it used to store values in linked list and the search order for link list is O(n), but in java

8 it forms binary tree (O(log(n))) instead of linked list. This makes search faster, this would be useful in case of

billions of records getting collide for same hash key.

Reply

 Anand says

FEBRUARY 2, 2017 AT 1:32 PM

Prior to Java 8 collision results in a list structure at the bucket where as java 8 changes that implemention to tree
Reply

30. BASAVARAJ says

DECEMBER 8, 2016 AT 8:39 PM

Guys Functional programing are Already there in SCALA Language

Reply

31. krishna says

DECEMBER 5, 2016 AT 12:51 AM


interface MyInt1{

default void log()

System.out.println(“this is log file interface”);

interface MyInt2{

default int log()

System.out.println(“hai this is another interface”);


return 10;

public class FunctInterface implements MyInt1,MyInt2{

public static void main(String[] args) {

FunctInterface f=new FunctInterface();

f.log();

//throws error please tell me how to solve

@Override
public void log() {

// TODO Auto-generated method stub

MyInt1.super.log();

Reply

 kammiti krishna says

JANUARY 30, 2017 AT 2:20 AM

In the both interfaces method return type should be same.


Reply

32. Bharath says

NOVEMBER 21, 2016 AT 11:29 PM

Good explanation

Reply

33. Rajesh says

NOVEMBER 21, 2016 AT 11:28 PM

Nice tutorial.
Reply

34. Pradeep Kumar says

NOVEMBER 21, 2016 AT 11:02 PM

Hi Pankaj,

very good article on Java8 and please provide me more information on the following topic of Java8.

*******Collection API improvements**** if you provide more information it would be great help for all those

whose are reading this article.

thanks in advance Pankaj. Sr. Software Engineer @ Tech Mahindra.


Reply

35. Dhanya says

OCTOBER 28, 2016 AT 2:04 PM

Very clear explanation with samples.

But contrary to you – there is benefit when using Lambda. In normal anonymous class implementation, new .Class

files are created where as with Lambda no new .Class files are generated.

Reply

36. Ranga says
SEPTEMBER 21, 2016 AT 11:05 AM

Nice explanation of Java8 features.

Reply

37. Deepak Shah says

AUGUST 11, 2016 AT 10:00 AM

Nice article.Brief and to the point.

Reply

 Debendra Dhinda says
SEPTEMBER 6, 2016 AT 9:10 AM

A beautiful Updation

Reply

38. neha says

AUGUST 11, 2016 AT 2:10 AM

great tutorial

Reply

39. Jayhind Rajpoot says


JULY 20, 2016 AT 7:11 AM

Nice explanation for new features added in Java 8

Reply

40. Venkat says

JULY 14, 2016 AT 4:29 AM

Simply superb!!!

Reply

41. hitesh says
JULY 13, 2016 AT 12:22 AM

Thanks for this valuable Article

Reply

42. Manoj says

JUNE 23, 2016 AT 11:17 PM

Good Article

Reply

43. ganesan says
JUNE 13, 2016 AT 5:07 PM

very nice

Reply

44. Chintan Kansara says

MAY 7, 2016 AT 1:18 PM

Nice article

Reply

45. AMIT BANSAL says


APRIL 11, 2016 AT 6:21 PM

Your understanding of java technologies are helping lot of people….Thanks a lot.

Reply

46. Kailash CH Das says

FEBRUARY 5, 2016 AT 2:50 AM

New features explanation is very nice. Thanks a lot. Keep it up

Reply

47. Ravi says
JANUARY 25, 2016 AT 8:36 PM

Nice article keep it up

Reply

48. prabhath says

JANUARY 6, 2016 AT 10:22 PM

Nice article on java 8 new features.

Thanks a lot.

Reply
49. dhrumil says

NOVEMBER 22, 2015 AT 7:26 PM

// forEach example to print each element of list

// in this case we are using method reference becasue

// we are not doing anything with each element of collection

// and just passing ito println method

System.out.println(“Printing elements of list using forEach method : “);

listOfPrimes.stream().forEach(System.out::println);
// let’s do something to each element before printing

// we will add comma after each element

System.out.println(“Printing elements after adding comma: “);

listOfPrimes.stream().forEach( i -> System.out.print( i + “,”));

// you can also use forEach with parallel stream

// order will not be guaranteed

System.out.println(“\nPrinting elements of list using parallel stream: “);

listOfPrimes.parallelStream().forEach( i-> System.out.println(i*2));

Reply
50. Prabu says

JULY 23, 2015 AT 2:17 AM

can you explain little more about FuctionalInterface and functional programming

1.what is functional programming ?why .explain with real time scenario

2.what is functional Interface and what purpose it has been introduced in java and what we can achieve with

functional Interface

3.without functional interface what we cant achieve in java 8?

Reply

51. babita says
JULY 13, 2015 AT 12:59 AM

Good explanation. I would like to know the differences between Future and CompletableFuture

Reply

52. Nobi Y says

JULY 3, 2015 AT 12:00 AM

Thanks a lot…Really beneficial

Reply

53. Tayyab says
DECEMBER 30, 2014 AT 5:28 AM

Very good stuff man, really helping and to the point!

Reply

54. Nakul Shinde says

SEPTEMBER 3, 2014 AT 11:37 PM

Nice article.. You explained really well.. Thanks and keep it up..

Reply

55. Nari Chinni says


JUNE 2, 2014 AT 2:42 AM

Really Nice & very useful stuff, But need to provide the examples for the 6 and 7th features.

Reply

 Pankaj says

JUNE 2, 2014 AT 8:23 AM

I have already listed the important new methods in the Collection and Concurrency APIs with brief explanation, just

use them and it should be easy to go.

Reply
56. Rajiv says

MAY 27, 2014 AT 9:56 PM

Awesome contents !! please keep helping us the same way !

Reply

57. Sathy\narayanan says

APRIL 20, 2014 AT 11:32 AM

Very good stuff man, really i’m very happy that i gained many things in java from you!!!

Reply
 sifun nanda says

AUGUST 6, 2016 AT 7:33 AM

Stream parallelStream = (Stream) myList.parallelStream();

In integer place i am getting error like: change project compliance and jre to 1.5. this erroe is coming in every integer

place in code.

p –> p > 90)—-here showing create local variable,create field ,parameter wht i should do?

for(int i=0; i<100; i++) myList.add(i);—here in add its error lke chang to AddAll()…wht should i do?

Java 8 features with examples


BY CHAITANYA SINGH | FILED UNDER: JAVA 8 FEATURES

Java 8 got released on March 18, 2014. There are several new features that are introduced in this release. I have covered all
the Java 8 features in the separate guides. Here are the links to all the Java 8 tutorials in the systematic order:

Java 8 features
1. Java 8 – Lambda Expression
2. Java 8 – Method references
3. Java 8 – Functional interfaces
4. Java 8 – Interface changes: Default and static methods
5. Java 8 – Streams
6. Java 8 – Stream filter
7. Java 8 – forEach()
8. Java 8 – Collectors class with example
9. Java 8 – StringJoiner class with example
10. Java 8 – Optional class with example
11. Java 8 – Arrays Parallel Sort
Java Lambda Expressions Tutorial with examples
BY CHAITANYA SINGH | FILED UNDER: JAVA 8 FEATURES

Lambda expression is a new feature which is introduced in Java 8. A lambda expression is an anonymous function. A
function that doesn’t have a name and doesn’t belong to any class. The concept of lambda expression was first introduced in
LISP programming language.

Java Lambda Expression Syntax


To create a lambda expression, we specify input parameters (if there are any) on the left side of the lambda operator ->, and
place the expression or block of statements on the right side of lambda operator. For example, the lambda expression (x, y)
-> x + y specifies that lambda expression takes two arguments x and y and returns the sum of these.

//Syntax of lambda expression


(parameter_list) -> {function_body}

Lambda expression vs method in Java


A method (or function) in Java has these main parts:
1. Name
2. Parameter list
3. Body
4. return type.

A lambda expression in Java has these main parts:


Lambda expression only has body and parameter list.
1. No name – function is anonymous so we don’t care about the name
2. Parameter list
3. Body – This is the main part of the function.
4. No return type – The java 8 compiler is able to infer the return type by checking the code. you need not to mention it
explicitly.

Where to use the Lambdas in Java


To use lambda expression, you need to either create your own functional interface or use the pre defined functional interface
provided by Java. An interface with only single abstract method is called functional interface(or Single Abstract method
interface), for example: Runnable, callable, ActionListener etc.

To use function interface:


Pre Java 8: We create anonymous inner classes.
Post Java 8: You can use lambda expression instead of anonymous inner classes.

Java Lambda expression Example


Without using Lambda expression: Prior to java 8 we used the anonymous inner classe to implement the only abstract
method of functional interface.
import java.awt.*;
import java.awt.event.*;
public class ButtonListenerOldWay {
public static void main(String[] args) {
Frame frame=new Frame("ActionListener Before Java8");

Button b=new Button("Click Here");


b.setBounds(50,100,80,50);

b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("Hello World!");
}
});
frame.add(b);

frame.setSize(200,200);
frame.setLayout(null);
frame.setVisible(true);
}
}

By using Lambda expression: Instead of creating anonymous inner class, we can create a lambda expression like this:

import java.awt.*;
public class ButtonListenerNewWay {
public static void main(String[] args) {
Frame frame=new Frame("ActionListener java8");

Button b=new Button("Click Here");


b.setBounds(50,100,80,50);

b.addActionListener(e -> System.out.println("Hello World!"));


frame.add(b);

frame.setSize(200,200);
frame.setLayout(null);
frame.setVisible(true);
}
}

Note:
1. As you can see that we used less code with lambda expression.
2. Backward compatibility: You can use the lambda expression with your old code. Lambdas are backward compatible so
you can use them in existing API when you migrate your project to java 8.

Lets see few more examples of Lambda expressions.

Example 1: Java Lambda Expression with no parameter


@FunctionalInterface
interface MyFunctionalInterface {

//A method with no parameter


public String sayHello();
}
public class Example {

public static void main(String args[]) {


// lambda expression
MyFunctionalInterface msg = () -> {
return "Hello";
};
System.out.println(msg.sayHello());
}
}

Output:

Hello

Example 2: Java Lambda Expression with single parameter


@FunctionalInterface
interface MyFunctionalInterface {

//A method with single parameter


public int incrementByFive(int a);
}
public class Example {

public static void main(String args[]) {


// lambda expression with single parameter num
MyFunctionalInterface f = (num) -> num+5;
System.out.println(f.incrementByFive(22));
}
}

Output:

27

Example 3: Java Lambda Expression with Multiple Parameters


interface StringConcat {

public String sconcat(String a, String b);


}
public class Example {

public static void main(String args[]) {


// lambda expression with multiple arguments
StringConcat s = (str1, str2) -> str1 + str2;
System.out.println("Result: "+s.sconcat("Hello ", "World"));
}
}

Output:

Result: Hello World

Example 4: Iterating collections using foreach loop


import java.util.*;  
public class Example{  
    public static void main(String[] args) {       
      List<String> list=new ArrayList<String>();  
       list.add("Rick");         
list.add("Negan");       
  list.add("Daryl");         
list.add("Glenn");         
list.add("Carl");               
  list.forEach(         
// lambda expression       
    (names)->System.out.println(names)         
);     
}  
}

We can iterate Maps and other collection classes using lambda expression, refer this guide: Iterating Map and List using
lambda expression

Method References in Java 8


BY CHAITANYA SINGH | FILED UNDER: JAVA 8 FEATURES

In the previous tutorial we learned lambda expressions in Java 8. Here we will discuss another new feature of java
8, method reference. Method reference is a shorthand notation of a lambda expression to call a method. For example:
If your lambda expression is like this:

str -> System.out.println(str)

then you can replace it with a method reference like this:

System.out::println

The :: operator is used in method reference to separate the class or object from the method name(we will learn this with the
help of examples).

Four types of method references


1. Method reference to an instance method of an object – object::instanceMethod
2. Method reference to a static method of a class – Class::staticMethod
3. Method reference to an instance method of an arbitrary object of a particular type – Class::instanceMethod
4. Method reference to a constructor – Class::new

1. Method reference to an instance method of an object


@FunctionalInterface
interface MyInterface{
void display();
}
public class Example {
public void myMethod(){
System.out.println("Instance Method");
}
public static void main(String[] args) {
Example obj = new Example();
// Method reference using the object of the class
MyInterface ref = obj::myMethod;
// Calling the method of functional interface
ref.display();
}
}

Output:

Instance Method
2. Method reference to a static method of a class
import java.util.function.BiFunction;
class Multiplication{
public static int multiply(int a, int b){
return a*b;
}
}
public class Example {
public static void main(String[] args) {
BiFunction<Integer, Integer, Integer> product = Multiplication::multiply;
int pr = product.apply(11, 5);
System.out.println("Product of given number is: "+pr);
}
}

Output:

Product of given number is: 55

3. Method reference to an instance method of an arbitrary object of a


particular type
import java.util.Arrays;
public class Example {

public static void main(String[] args) {


String[] stringArray = { "Steve", "Rick", "Aditya", "Negan", "Lucy", "Sansa", "Jon"};
/* Method reference to an instance method of an arbitrary
* object of a particular type
*/
Arrays.sort(stringArray, String::compareToIgnoreCase);
for(String str: stringArray){
System.out.println(str);
}
}
}

Output:

Aditya
Jon
Lucy
Negan
Rick
Sansa
Steve

4. Method reference to a constructor


@FunctionalInterface
interface MyInterface{
Hello display(String say);
}
class Hello{
public Hello(String say){
System.out.print(say);
}
}
public class Example {
public static void main(String[] args) {
//Method reference to a constructor
MyInterface ref = Hello::new;
ref.display("Hello World!");
}
}

Output:

Hello World!

Java Functional Interfaces


BY CHAITANYA SINGH | FILED UNDER: JAVA 8 FEATURES

An interface with only single abstract method is called functional interface. You can either use the predefined functional
interface provided by Java or create your own functional interface and use it. You can check the predefined functional
interfaces here: predefined functional interfaces they all have only one abstract method. That is the reason,they are also
known as Single Abstract Method interfaces (SAM Interfaces).

To use lambda expression in Java, you need to either create your own functional interface or use the pre defined functional
interface provided by Java. While creating your own functional interface, mark it with @FunctionalInterface annotation,
this annotation is introduced in Java 8. Although its optional, you should use it so that you get a compilation error if the
interface you marked with this annotation is not following the rules of functional interfaces.

What are the rules of defining a functional interface?


The functional interface should have Only one abstract method. Along with the one abstract method, they can have any
number of default and static methods.

Example 1: Creating your own functional interface


@FunctionalInterface
interface MyFunctionalInterface {

public int addMethod(int a, int b);


}
public class BeginnersBookClass {

public static void main(String args[]) {


// lambda expression
MyFunctionalInterface sum = (a, b) -> a + b;
System.out.println("Result: "+sum.addMethod(12, 100));
}
}

Output:

Result: 112

Example 2: Using predefined functional interface


import java.util.function.IntBinaryOperator;

public class BeginnersBookClass {

public static void main(String args[]) {


// lambda expression
IntBinaryOperator sum = (a, b) -> a + b;
System.out.println("Result: " + sum.applyAsInt(12, 100));

}
}

Output:

Result: 112

Functional interface example: using anonymous inner class vs using


lambda expression
We have been using functional interfaces even prior to java8, they were used by creating anonymous inner classes using
these interfaces. You must have seen functional interfaces such as Runnable, ActionListener, Comparator etc. They all have
single abstract method. Lets see an example of ActionListener to see how it was used with Anonymous inner class and how
it can be implemented using lambda expression.
ActionListener Example: Before Java 8: Using anonymous inner class

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Example extends JFrame
{
JButton button;
public Example()
{
setTitle("Button Action Example without Lambda Expression");
setSize(400,300);
setVisible(true);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);

button = new JButton("Button");


button.setBounds(100,100,90,40);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("You clicked the button.");
}

});
add(button);
}
public static void main(String args[])
{
new Example();
}
}

ActionListener Example: Lambda Expression

import javax.swing.*;
import java.awt.*;
class Example extends JFrame
{
JButton button;
public Example()
{
setTitle("Button Action Example using Lambda Expression");
setSize(400,300);
setVisible(true);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);

button = new JButton("Button");


button.setBounds(100,100,90,40);
//Lambda expression
button.addActionListener(e->
System.out.println("You clicked the button."));

add(button);
}
public static void main(String args[])
{
new Example();
}
}

Java 8 Interface Changes – default method and static method


BY CHAITANYA SINGH | FILED UNDER: JAVA 8 FEATURES

Prior to java 8, interface in java can only have abstract methods. All the methods of interfaces are public & abstract by
default. Java 8 allows the interfaces to have default and static methods. The reason we have default methods in interfaces is
to allow the developers to add new methods to the interfaces without affecting the classes that implements these interfaces.

Why default method?


For example, if several classes such as A, B, C and D implements an interface XYZInterface then if we add a new method
to the XYZInterface, we have to change the code in all the classes(A, B, C and D) that implements this interface. In this
example we have only four classes that implements the interface which we want to change but imagine if there are hundreds
of classes implementing an interface then it would be almost impossible to change the code in all those classes. This is why
in java 8, we have a new concept “default methods”. These methods can be added to any existing interface and we do not
need to implement these methods in the implementation classes mandatorily, thus we can add these default methods to
existing interfaces without breaking the code.

We can say that concept of default method is introduced in java 8 to add the new methods in the existing
interfaces in such a way so that they are backward compatible. Backward compatibility is adding new features
without breaking the old code.

Static methods in interfaces are similar to the default methods except that we cannot override these methods in the classes
that implements these interfaces.

Java 8 Example: Default method in Interface


The method newMethod() in MyInterface is a default method, which means we need not to implement this method in the
implementation class Example. This way we can add the default methods to existing interfaces without bothering about the
classes that implements these interfaces.

interface MyInterface{
/* This is a default method so we need not
* to implement this method in the implementation
* classes
*/
default void newMethod(){
System.out.println("Newly added default method");
}
/* Already existing public and abstract method
* We must need to implement this method in
* implementation classes.
*/
void existingMethod(String str);
}
public class Example implements MyInterface{
// implementing abstract method
public void existingMethod(String str){
System.out.println("String is: "+str);
}
public static void main(String[] args) {
Example obj = new Example();

//calling the default method of interface


obj.newMethod();
//calling the abstract method of interface
obj.existingMethod("Java 8 is easy to learn");

}
}

Output:

Newly added default method


String is: Java 8 is easy to learn

Java 8 Example: Static method in Interface


As mentioned above, the static methods in interface are similar to default method so we need not to implement them in the
implementation classes. We can safely add them to the existing interfaces without changing the code in the implementation
classes. Since these methods are static, we cannot override them in the implementation classes.

interface MyInterface{
/* This is a default method so we need not
* to implement this method in the implementation
* classes
*/
default void newMethod(){
System.out.println("Newly added default method");
}

/* This is a static method. Static method in interface is


* similar to default method except that we cannot override
* them in the implementation classes.
* Similar to default methods, we need to implement these methods
* in implementation classes so we can safely add them to the
* existing interfaces.
*/
static void anotherNewMethod(){
System.out.println("Newly added static method");
}
/* Already existing public and abstract method
* We must need to implement this method in
* implementation classes.
*/
void existingMethod(String str);
}
public class Example implements MyInterface{
// implementing abstract method
public void existingMethod(String str){
System.out.println("String is: "+str);
}
public static void main(String[] args) {
Example obj = new Example();

//calling the default method of interface


obj.newMethod();
//calling the static method of interface
MyInterface.anotherNewMethod();
//calling the abstract method of interface
obj.existingMethod("Java 8 is easy to learn");

}
}

Output:

Newly added default method


Newly added static method
String is: Java 8 is easy to learn

Java 8 – Abstract classes vs interfaces


With the introduction of default methods in interfaces, it seems that the abstract classes are same as interface in java 8.
However this is not entirely true, even though we can now have concrete methods(methods with body) in interfaces just like
abstract class, this doesn’t mean that they are same. There are still few differences between them, one of them is that
abstract class can have constructor while in interfaces we can’t have constructors.

The purpose of interface is to provide full abstraction, while the purpose of abstract class is to provide partial abstraction.
This still holds true. The interface is like a blueprint for your class, with the introduction of default methods you can simply
say that we can add additional features in the interfaces without affecting the end user classes.

Default Method and Multiple Inheritance


The multiple inheritance problem can occur, when we have two interfaces with the default methods of same signature.
Lets take an example.

interface MyInterface{

default void newMethod(){


System.out.println("Newly added default method");
}
void existingMethod(String str);
}
interface MyInterface2{

default void newMethod(){


System.out.println("Newly added default method");
}
void disp(String str);
}
public class Example implements MyInterface, MyInterface2{
// implementing abstract methods
public void existingMethod(String str){
System.out.println("String is: "+str);
}
public void disp(String str){
System.out.println("String is: "+str);
}

public static void main(String[] args) {


Example obj = new Example();

//calling the default method of interface


obj.newMethod();
}
}

Output:

Error: Duplicate default methods named newMethod with the parameters () and () are inherited from the types
MyInterface2 and MyInterface

This is because we have the same method in both the interface and the compiler is not sure which method to be invoked.

How to solve this issue?


To solve this problem, we can implement this method in the implementation class like this:

interface MyInterface{

default void newMethod(){


System.out.println("Newly added default method");
}
void existingMethod(String str);
}
interface MyInterface2{

default void newMethod(){


System.out.println("Newly added default method");
}
void disp(String str);
}
public class Example implements MyInterface, MyInterface2{
// implementing abstract methods
public void existingMethod(String str){
System.out.println("String is: "+str);
}
public void disp(String str){
System.out.println("String is: "+str);
}
//Implementation of duplicate default method
public void newMethod(){
System.out.println("Implementation of default method");
}
public static void main(String[] args) {
Example obj = new Example();

//calling the default method of interface


obj.newMethod();

}
}

Output:

Implementation of default method

Java 8 Stream Tutorial


BY CHAITANYA SINGH | FILED UNDER: JAVA 8 FEATURES

In the previous tutorial we learned the interface changes in java 8. In this guide, we will discuss Stream API which is
another new feature of java 8. All the classes and interfaces of this API is in the java.util.stream package. By using streams
we can perform various aggregate operations on the data returned from collections, arrays, Input/Output operations. Before
we see how stream API can be used in Java, let’s see an example to understand the use of streams.

Java Stream Example


To understand how stream works, lets take an example without using stream and then we will see the same example with
streams.

Finding certain strings without using Stream

import java.util.ArrayList;
import java.util.List;
public class Example{
public static void main(String[] args) {
List<String> names = new ArrayList<String>();
names.add("Ajeet");
names.add("Negan");
names.add("Aditya");
names.add("Steve");
int count = 0;
for (String str : names) {
if (str.length() < 6)
count++;
}
System.out.println("There are "+count+" strings with length less than 6");
}
}

Output:

There are 3 strings with length less than 6

Same example using Stream

import java.util.ArrayList;
import java.util.List;
public class Example{
public static void main(String[] args) {
List<String> names = new ArrayList<String>();
names.add("Ajeet");
names.add("Negan");
names.add("Aditya");
names.add("Steve");

//Using Stream and Lambda expression


long count = names.stream().filter(str->str.length()<6).count();
System.out.println("There are "+count+" strings with length less than 6");

}
}

Output:

There are 3 strings with length less than 6

What is the difference between these codes?


The output of both the examples are same, however there is a major difference between these examples if you consider the
performance of the code.
In the first example, we are iterating the whole list to find the strings with length less than 6. There is no parallelism in this
code.
In the second example, the stream() method returns a stream of all the names, the filter() method returns another stream of
names with length less than 6, the count() method reduces this stream to the result. All these operations are happening
parallelly which means we are able to parallelize the code with the help of streams. Parallel execution of operations using
stream is faster than sequential execution without using streams.

How to work with Stream in Java


As we have seen in the above example, the working of stream can be explained in three stages:
1. Create a stream

2. Perform intermediate operations on the initial stream to transform it into another stream and so on on further
intermediate operations. In the above example, the filter() operation is intermediate operation, there can be more than one
intermediate operations.

3. Perform terminal operation on the final stream to get the result. In the above example, the count() operation is terminal
operation.

Java Stream Features


1. Stream does not store the elements. it simply performs the aggregate operations(such as filter() and count() that we have
seen in the above example) to get the desired stream of data.

2. The aggregate operations that we perform on the collection, array or any other data source do not change the data of the
source, they simply return a new stream. For example the code we have seen above is filtering the strings with length less
than 6 using the stream operations but it didn’t change the elements of the list.

3. All the stream operations are lazy in nature which means they are not executed until they are needed. For example, if we
want to display only the first 2 elements of a list using stream, the stream operation would stop at the end of second iteration
after displaying the second element of list.

Let’s see few examples of Java Stream:

Java Stream Example 1: Iterating and displaying selected integers


import java.util.stream.*;
public class Example {
public static void main(String[] args){
Stream.iterate(1, count->count+1)
.filter(number->number%3==0)
.limit(6)
.forEach(System.out::println);
}
}

Output:

3
6
9
12
15
18

Java Stream Example 2: Concatenating two streams


import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class Example {
public static void main(String[] args) {
//list 1
List<String> alphabets = Arrays.asList("A","B","C");
//list 2
List<String> names = Arrays.asList("Sansa","Jon","Arya");

//creating two streams from the two lists and concatenating them into one
Stream<String> opstream = Stream.concat(alphabets.stream(), names.stream());

//displaying the elements of the concatenated stream


opstream.forEach(str->System.out.print(str+" "));
}
}

Output:

A B C Sansa Jon Arya

Related Posts:

1. Java Stream allMatch() Example

2. Java Stream noneMatch() Example

3. Java Stream anyMatch() example

Java 8 Stream Filter with examples


BY CHAITANYA SINGH | FILED UNDER: JAVA 8 FEATURES

In the previous tutorial, we learned about Java Stream. I would recommend you to read that guide before going through
this tutorial. In this guide, we will discuss the Java stream filter. The filter() is an intermediate operation that reads the data
from a stream and returns a new stream after transforming the data based on the given condition. Lets take a simple example
first and then we will see the examples of stream filter with other methods of the stream.

A Simple Example of Java Stream Filter()


In this example we are creating a stream from the list of names using stream() method and then we are creating another
stream of long names using stream filter(). As I mentioned above, the stream filter transforms the data of one stream into
another stream.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class Example {
public static void main(String[] args) {

List<String> names = Arrays.asList("Melisandre","Sansa","Jon","Daenerys","Joffery");


//Creating the stream of all names
Stream<String> allNames = names.stream();

//Creating another stream by filtering long names using filter()


Stream<String> longNames = allNames.filter(str -> str.length() > 6);

//displaying the long names


longNames.forEach(str->System.out.print(str+" "));
}
}

Output:

Melisandre Daenerys Joffery

Lets take few more examples of Java stream filter.

Example 1: Stream filter() and collect()


We can create a stream and apply a filter in a one line as shown in the example below. The collect() method here collects the
final stream and converts it into a list

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Example {

public static void main(String[] args) {

List<String> names = Arrays.asList("Melisandre","Sansa","Jon","Daenerys","Joffery");

List<String> longnames = names.stream() // converting the list to stream


.filter(str -> str.length() > 6) // filter the stream to create a new stream
.collect(Collectors.toList()); // collect the final stream and convert it to a List

longnames.forEach(System.out::println);

Output:

Melisandre
Daenerys
Joffery

Example 2: Stream filter() with multiple conditions


In the above examples we have seen that there is only one condition in the filter() method. We can have more than one
conditions in the filter() method joined using the logical operators in java. In the following example, we have two
conditions in the filter method joined using and (&&) logical operator.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Example {

public static void main(String[] args) {

List<String> names = Arrays.asList("Melisandre","Sansa","Jon","Daenerys","Joffery");

List<String> longnames = names.stream()


.filter(str -> str.length() > 6 && str.length() < 8) //Multiple conditions
.collect(Collectors.toList());

longnames.forEach(System.out::println);

Output:

Joffery

Example 3: Stream filter() and map() method in Java


import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Example {

public static void main(String[] args) {

List<Integer> num = Arrays.asList(1,2,3,4,5,6);


List<Integer> squares = num.stream()
.map(n -> n * n)
.collect(Collectors.toList());
System.out.println(squares);

Output:

[1, 4, 9, 16, 25, 36]

More Tutorials on Java Stream Filter:

1. Java 8 – Filter a Map by keys and values

2. Java 8 – Filter null values from a stream

Java 8 – forEach
BY CHAITANYA SINGH | FILED UNDER: JAVA 8 FEATURES

In Java 8, we have a newly introduced forEach method to iterate over collections and Streams in Java. In this guide, we
will learn how to use forEach() and forEachOrdered() methods to loop a particular collection and stream.
Java 8 – forEach to iterate a Map
import java.util.Map;
import java.util.HashMap;
public class Example {
   public static void main(String[] args) {
    Map<Integer, String> hmap = new HashMap<Integer, String>();
   hmap.put(1, "Monkey");
   hmap.put(2, "Dog");
   hmap.put(3, "Cat");  
 hmap.put(4, "Lion");  
 hmap.put(5, "Tiger");  
 hmap.put(6, "Bear");
/* forEach to iterate and display each key and value pair
    * of HashMap.    
*/  
 hmap.forEach((key,value)->System.out.println(key+" - "+value));
/* forEach to iterate a Map and display the value of a particular  
  * key    
*/
   hmap.forEach((key,value)->{
    if(key == 4){
    System.out.println("Value associated with key 4 is: "+value);
    }  
  });    
   /* forEach to iterate a Map and display the key associated with a
    * particular value    
*/
   hmap.forEach((key,value)->{
    if("Cat".equals(value)){
    System.out.println("Key associated with Value Cat is: "+key);
    }
   }); 
  }
}

Java 8 – forEach to iterate a List


In this example, we are iterating an ArrayList using forEach() method. Inside forEach we are using a lambda
expression to print each element of the list.

import java.util.List;
import java.util.ArrayList;
public class Example {
public static void main(String[] args) {
List<String> fruits = new ArrayList<String>();
fruits.add("Apple");
fruits.add("Orange");
fruits.add("Banana");
fruits.add("Pear");
fruits.add("Mango");
//lambda expression in forEach Method
fruits.forEach(str->System.out.println(str));
}
}

Output:

Apple
Orange
Banana
Pear
Mango

We can also use method reference in the forEach() method like this:

fruits.forEach(System.out::println);

Java 8 – forEach method to iterate a Stream


In this example we are iterating a Stream in Java using forEach() method.

import java.util.List;
import java.util.ArrayList;
public class Example {
public static void main(String[] args) {
List<String> names = new ArrayList<String>();
names.add("Maggie");
names.add("Michonne");
names.add("Rick");
names.add("Merle");
names.add("Governor");
names.stream() //creating stream
.filter(f->f.startsWith("M")) //filtering names that starts with M
.forEach(System.out::println); //displaying the stream using forEach
}
}

Output:

Maggie
Michonne
Merle

Java – Stream forEachOrdered() Method Example


For sequential streams the order of elements is same as the order in the source, so the output would be same whether you
use forEach or forEachOrdered. However when working with parallel streams, you would always want to use the
forEachOrdered() method when the order matters to you, as this method guarantees that the order of elements would be
same as the source. Lets take an example to understand the difference between forEach() and forEachOrdered().

import java.util.List;
import java.util.ArrayList;
public class Example {
public static void main(String[] args) {
List<String> names = new ArrayList<String>();
names.add("Maggie");
names.add("Michonne");
names.add("Rick");
names.add("Merle");
names.add("Governor"); 
//forEach - the output would be in any order
System.out.println("Print using forEach");
names.stream() 
.filter(f->f.startsWith("M"))
  .parallel()
.forEach(n->System.out.println(n));

/* forEachOrdered - the output would always be in this order:


* Maggie, Michonne, Merle
*/
System.out.println("Print using forEachOrdered");
names.stream() 
.filter(f->f.startsWith("M")) 
.parallel()
.forEachOrdered(n->System.out.println(n));
}
}

Output:

Print using forEach


Merle
Maggie
Michonne
Print using forEachOrdered
Maggie
Michonne
Merle

References:

 Java 8 – foreach JavaDoc

 Java 8 – for vs foreach loop JavaDoc


Java 8 – Stream Collectors Class with examples
BY CHAITANYA SINGH | FILED UNDER: JAVA 8 FEATURES

Collectors is a final class that extends the Object class. In this tutorial we will see the examples of Java Stream collectors
class using lambda expressions, Java Streams and other new features of Java 8.

java.lang.Object
|
|___java.util.stream.Collectors

Java – Stream Collectors groupingBy and counting Example


In this example, we are grouping the elements of a list using groupingBy() method of Collectors class and printing the
occurrences of each element in the list.

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Example {

public static void main(String[] args) {

List<String> names =
Arrays.asList("Jon", "Ajeet", "Steve",
"Ajeet", "Jon", "Ajeet");

Map<String, Long> map =


names.stream().collect(
Collectors.groupingBy(
Function.identity(), Collectors.counting()
)
);

System.out.println(map);

}
}

Output:

{Steve=1, Jon=2, Ajeet=3}

Java – Stream Collectors example of fetching data as List


import java.util.stream.Collectors;  
import java.util.List;  
import java.util.ArrayList;  
class Student{  
int id;     
String name;   
  int age;         
  public Student(int id, String name, int age) {  
        this.id = id;   
      this.name = name;         
this.age = age;     

}  
public class Example {  
   public static void main(String[] args) {   
      List<Student> studentlist = new ArrayList<Student>();   
     //Adding Students      
  studentlist.add(new Student(11,"Jon",22));     
    studentlist.add(new Student(22,"Steve",18));       
  studentlist.add(new Student(33,"Lucy",22));       
  studentlist.add(new Student(44,"Sansa",23));         
studentlist.add(new Student(55,"Maggie",18));                 
//Fetching student names as List       
List<String> names = studentlist.stream()
.map(n->n.name)
.collect(Collectors.toList());
System.out.println(names);         
  }  
}

Output:

[Jon, Steve, Lucy, Sansa, Maggie]

Java Collectors Example – Collecting Data as Set


In this example we are converting the list of students to the stream and then we are applying the Java Stream filter to get
the selected records from the stream, after that we are converting that stream to set using Collectors.toSet() method.

import java.util.stream.Collectors;  
import java.util.List;  
import java.util.Set; 
import java.util.ArrayList;  
class Student{   
  int id;     
String name;  
int age;           
public Student(int id, String name, int age) {   
      this.id = id;         
this.name = name;       
  this.age = age;     

}  
public class Example {     
public static void main(String[] args) {       
  List<Student> studentlist = new ArrayList<Student>();       
  //Adding Students        
studentlist.add(new Student(11,"Jon",22));         
studentlist.add(new Student(22,"Steve",18));         
studentlist.add(new Student(33,"Lucy",22));         
studentlist.add(new Student(44,"Sansa",23));         
studentlist.add(new Student(55,"Maggie",18));                 
//Fetching student data as a Set       
Set<Student> students = studentlist.stream()
.filter(n-> n.id>22)
.collect(Collectors.toSet());
//Iterating Set       
for(Student stu : students) {
System.out.println(stu.id+" "+stu.name+" "+stu.age);
}           

}

Output:
44 Sansa 23
33 Lucy 22
55 Maggie 18

Java Collectors Example – Getting the average age of students using


averagingInt() method
import java.util.stream.Collectors;  
import java.util.List;  
import java.util.ArrayList; 
class Student{  
int id;  
String name;  
int age;
public Student(int id, String name, int age) {  
this.id = id;  
this.name = name; 
  this.age = age;  

}  
public class Example {  
public static void main(String[] args) {  
List<Student> studentlist = new ArrayList<Student>();  
//Adding Students 
studentlist.add(new Student(11,"Jon",22));  
studentlist.add(new Student(22,"Steve",18));  
studentlist.add(new Student(33,"Lucy",22));  
studentlist.add(new Student(44,"Sansa",23));  
studentlist.add(new Student(55,"Maggie",18));
//Getting the average Age
Double avgAge = studentlist.stream()  
.collect(Collectors.averagingInt(s->s.age));  
System.out.println("Average Age of Students is: "+avgAge);
}  
}

Output:

Average Age of Students is: 20.6

I have shown the examples of very few methods of Java Collectors class. To get the complete list of methods refer the
javadoc: Java 8 Stream Collectors – JavaDoc
Java 8 StringJoiner with example
BY CHAITANYA SINGH | FILED UNDER: JAVA 8 FEATURES

In java 8, a new class StringJoiner is introduced in the java.util package. Using this class we can join more than one strings
with the specified delimiter, we can also provide prefix and suffix to the final string while joining multiple strings. In this
tutorial we will see several examples of StringJoiner class and at the end of this guide, we will see the methods of
StringJoiner class.

Java StringJoiner Example 1: Joining strings by specifying delimiter


In this example, we are concatenating multiple strings using StringJoiner. While creating the instance of StringJoiner, we
have specified the delimiter as hyphen(-).

import java.util.StringJoiner;
public class Example {
public static void main(String[] args) {
// Passing Hyphen(-) as delimiter
StringJoiner mystring = new StringJoiner("-");

// Joining multiple strings by using add() method


mystring.add("Logan");
mystring.add("Magneto");
mystring.add("Rogue");
mystring.add("Storm");

// Displaying the output String


System.out.println(mystring);
}
}

Output:

Logan-Magneto-Rogue-Storm

Java StringJoiner Example 2: Adding prefix and suffix to the output String
import java.util.StringJoiner;
public class Example {
public static void main(String[] args) {
/* Passing comma(,) as delimiter and opening bracket
* "(" as prefix and closing bracket ")" as suffix
*/
StringJoiner mystring = new StringJoiner(",", "(", ")");

// Joining multiple strings by using add() method


mystring.add("Negan");
mystring.add("Rick");
mystring.add("Maggie");
mystring.add("Daryl");

// Displaying the output String


System.out.println(mystring);
}
}

Output:
(Negan,Rick,Maggie,Daryl)

StringJoiner Example 3: Merging two StringJoiner objects


import java.util.StringJoiner;
public class Example {
public static void main(String[] args) {
/* Passing comma(,) as delimiter and opening bracket
* "(" as prefix and closing bracket ")" as suffix
*/
StringJoiner mystring = new StringJoiner(",", "(", ")");

mystring.add("Negan");
mystring.add("Rick");
mystring.add("Maggie");
mystring.add("Daryl");

System.out.println("First String: "+mystring);

/* Passing hyphen(-) as delimiter and string "pre"


* as prefix and string "suff" as suffix
*/
StringJoiner myanotherstring = new StringJoiner("-", "pre", "suff");

myanotherstring.add("Sansa");
myanotherstring.add("Imp");
myanotherstring.add("Jon");
myanotherstring.add("Ned");

System.out.println("Second String: "+myanotherstring);

/* Merging both the strings


* The important point to note here is that the output string will be
* having the delimiter prefix and suffix of the first string (the string
* which is calling the merge method of StringJoiner)
*/
StringJoiner mergedString = mystring.merge(myanotherstring);
System.out.println(mergedString);
}
}

Output:

First String: (Negan,Rick,Maggie,Daryl)


Second String: preSansa-Imp-Jon-Nedsuff
(Negan,Rick,Maggie,Daryl,Sansa-Imp-Jon-Ned)

In the above examples, we have seen the add() and merge() methods of StringJoiner class. Lets see the other methods of this
class.

StringJoiner Example: setEmptyValue(), length() and toString() methods


import java.util.StringJoiner;
public class Example {
public static void main(String[] args) {
//Comma(,) as delimiter
StringJoiner mystring = new StringJoiner(",");

/* Using setEmptyValue() method, we can set the default value


* of a StringJoiner instance, so if the StringJoiner is empty
* and we print the value of it, this default value will be
* displayed
*/
mystring.setEmptyValue("This is a default String");
/* We have not added any string to StringJoiner yet so
* this should display the default value of StringJoiner
*/
System.out.println("Default String: "+mystring);

// Adding strings to StringJoiner


mystring.add("Apple");
mystring.add("Banana");
mystring.add("Orange");
mystring.add("Kiwi");
mystring.add("Grapes");
System.out.println(mystring);

/* The length() method of StringJoiner class returns the


* length of the string (the number of characters in the
* StringJoiner instance)
*/
int length = mystring.length();
System.out.println("Length of the StringJoiner: "+length);

/* The toString() method is used for converting a StringJoiner


* instance to a String.
*/
String s = mystring.toString();
System.out.println(s);
}
}

Output:

Default String: This is a default String


Apple,Banana,Orange,Kiwi,Grapes
Length of the StringJoiner: 31
Apple,Banana,Orange,Kiwi,Grapes

References:
Java 8 – StringJoiner JavaDoc
Java 8 Optional Class
BY CHAITANYA SINGH | FILED UNDER: JAVA 8 FEATURES

In Java 8, we have a newly introduced Optional class in java.util package. This class is introduced to avoid


NullPointerException that we frequently encounters if we do not perform null checks in our code. Using this class we can
easily check whether a variable has null value or not and by doing this we can avoid the NullPointerException. In this guide,
we will see how to work with Optional class and the usage of various methods of this class.

Before we see the example of Optional class, lets see what happens when we don’t use Optional class and do not perform
null check.

Java Example: Without using Optional class


In this example, we didn’t assign the value to the String str and we are trying to get the substringout of it. Since there is no
value present in the str, the program is throwing NullPointerException.

public class Example {


public static void main(String[] args) {
String[] str = new String[10];
//Getting the substring
String str2 = str[9].substring(2, 5);
//Displaying substring
System.out.print(str2);
}
}

Output:

Exception in thread "main" java.lang.NullPointerException


at Example.main(Example.java:5)

Solution: Using Optional Class


Optional.ofNullable() method of the Optional class, returns a Non-empty Optional if the given object has a value, otherwise
it returns an empty Optional.
We can check whether the returned Optional value is empty or non-empty using the isPresent()method.

//Importing Optional class


import java.util.Optional; 
public class Example { 
public static void main(String[] args) {   
  String[] str = new String[10];     
Optional<String> isNull = Optional.ofNullable(str[9]);       
  if(isNull.isPresent()){     
 //Getting the substring          
 String str2 = str[9].substring(2, 5);         
 //Displaying substring           
System.out.print("Substring is: "+ str2);      
  }     
  else{     
  System.out.println("Cannot get the substring from an empty string");     
  }                
str[9] = "AgraIsCool";       
Optional<String> isNull2 = Optional.ofNullable(str[9]);      
  if(isNull2.isPresent()){       
 //Getting the substring            
String str2 = str[9].substring(2, 5);           
//Displaying substring           
System.out.print("Substring is: "+ str2);          
}         
else{         
System.out.println("Cannot get the substring from an empty string");         
}   
}  
}

Output:

Cannot get the substring from an empty string


Substring is: raI

Example: Optional isPresent() vs ifPresent() methods


In the above example, we have seen that by using isPresent() method we can check whether the particular Optional
object(or instance) is empty or no-empty.
There is another method present in the Optional class, which only executes if the given Optional object is non-empty, the
method is ifPresent(). Lets see an example to understand the difference.

//Importing Optional class


import java.util.Optional;
  public class Example {  
public static void main(String[] args) {
//Creating Optional object from a String
Optional<String> GOT = Optional.of("Game of Thrones");       
//Optional.empty() creates an empty Optional object       
Optional<String> nothing = Optional.empty();
/* isPresent() method: Checks whether the given Optional         
* Object is empty or not.         
*/       
if (GOT.isPresent()) {         
  System.out.println("Watching Game of Thrones");       
}
else {           
System.out.println("I am getting Bored");     
  }
/* ifPresent() method: It executes only if the given Optional         
* object is non-empty.         
*/       
//This will print as the GOT is non-empty       
GOT.ifPresent(s -> System.out.println("Watching GOT is fun!"));               
//This will not print as the nothing is empty       
nothing.ifPresent(s -> System.out.println("I prefer getting bored"));
}
}

Output:

Watching Game of Thrones


Watching GOT is fun!

Java 8 – Optional orElse() and orElseGet() methods


These two methods orElse() and orElseGet() returns the value of Optional Object if it is no empty, if the object is empty
then it returns the default value passed to this method as an argument.
//Importing Optional class
import java.util.Optional;
  public class Example {  
public static void main(String[] args) {
//Creating Optional object from a String
Optional<String> GOT = Optional.of("Game of Thrones");       
//Optional.empty() creates an empty Optional object       
Optional<String> nothing = Optional.empty();

//orElse() method
System.out.println(GOT.orElse("Default Value"));
System.out.println(nothing.orElse("Default Value"));

//orElseGet() method
System.out.println(GOT.orElseGet(() -> "Default Value"));
System.out.println(nothing.orElseGet(() -> "Default Value"));

}
}

Output:

Game of Thrones
Default Value
Game of Thrones
Default Value

Java 8 – Optional.map and Optional.flatMap


In this example, we will see how Optional works with map and flatMap.

//Importing Optional class


import java.util.Optional; 
public class Example {  
public static void main(String[] args) {
//Creating Optional object from a String       
Optional<String> GOT = Optional.of("Game of Thrones");       
//Optional.empty() creates an empty Optional object       
Optional<String> nothing = Optional.empty();
System.out.println(GOT.map(String::toLowerCase));       
System.out.println(nothing.map(String::toLowerCase));
Optional<Optional<String>> anotherOptional = Optional.of(Optional.of("BreakingBad"));       
System.out.println("Value of Optional object"+anotherOptional);       
System.out.println("Optional.map: "             
+anotherOptional.map(gender -> gender.map(String::toUpperCase)));       
//Optional<Optional<String>>    -> flatMap -> Optional<String>       
System.out.println("Optional.flatMap: "           
 +anotherOptional.flatMap(gender -> gender.map(String::toUpperCase)));
}
}

Output:

Optional[game of thrones]
Optional.empty
Value of Optional objectOptional[Optional[BreakingBad]]
Optional.map: Optional[Optional[BREAKINGBAD]]
Optional.flatMap: Optional[BREAKINGBAD]
Example: Optional with filter
In this example, we will see how Optional works with filter. To read about filters refer this guide: Java filters.
More tutorials on Filters:

1. Java – Filter a Map

2. Filter null values from a Stream in Java

//Importing Optional class


import java.util.Optional; 
public class Example {  
public static void main(String[] args) {
//Creating Optional object from a String       
Optional<String> GOT = Optional.of("Game of Thrones");             
  /* Filter returns an empty Optional instance if the output doesn't         
* contain any value, else it returns the Optional object of the          
* given value.         
*/       
System.out.println(GOT.filter(s -> s.equals("GAME OF THRONES")));        
System.out.println(GOT.filter(s -> s.equalsIgnoreCase("GAME OF THRONES")));
}
}

Output:

Optional.empty
Optional[Game of Thrones]

References:
Java 8 – Optional class JavaDoc
Java 8 – Arrays Parallel Sort with example
BY CHAITANYA SINGH | FILED UNDER: JAVA 8 FEATURES

Java 8 introduced a new method parallelSort() in the Arrays class of java.util package. This method is introduced to support
the parallel sorting of array elements.
Algorithm of parallel sorting:
1. The given array is divided into the sub arrays and the sub arrays are further divided into the their sub arrays, this happens
until the sub array reaches a minimum granularity.
2. The sub arrays are sorted individually by multiple threads. The parallel sort uses Fork/Join Framework for sorting sub
arrays parallelly.
3. The sorted sub arrays are merged.

Advantage of Parallel Sort Over Simple Sort:


The parallelSort() method uses the concept of multithreading which makes it much faster compared to the normal
sort when there are lot of elements.

Example 1: Sorting Primitive Data types with Parallel Sort


import java.util.Arrays;
public class Example {
public static void main(String[] args) {
int numbers[] = {22, 89, 1, 32, 19, 5};
//Parallel Sort method for sorting int array
Arrays.parallelSort(numbers);
//converting the array to stream and displaying using forEach
Arrays.stream(numbers).forEach(n->System.out.print(n+" "));
}
}

Output:

1 5 19 22 32 89

References:
Java 8 – Parallel Sort JavaDoc

Example 2: Parallel Sort by specifying the start and end index


We can also specify the start and end for the sorting, in this case the sub array starting from the start index and ending at the
end index is sorted, the rest of the array is ignored and doesn’t get sorted.

import java.util.Arrays;
public class Example {
public static void main(String[] args) {
int numbers[] = {22, 89, 1, 32, 19, 5};
/* Specifying the start and end index. The start index is
* 1 here and the end index is 5. which means the the elements
* starting from index 1 till index 5 would be sorted.
*/
Arrays.parallelSort(numbers, 1, 5);
//converting the array to stream and displaying using forEach
Arrays.stream(numbers).forEach(n->System.out.print(n+" "));
}
}
Output:

22 1 19 32 89 5

Das könnte Ihnen auch gefallen