Beruflich Dokumente
Kultur Dokumente
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.
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?
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);
Integer i = 4;
int j = i;
Number n = 3.14159f;
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.
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:
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 ...
import java.awt.*;
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:
Of course you can define your own annotations. They're basically like interfaces, but they can contain
values. An example annotation looks like:
@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)!
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.
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?
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.
import java.util.*;
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");
list.remove("B");
list.remove(3);
list.removeFirst();
list.removeLast();
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
s.add(10);
s.add(30);
s.add(98);
s.add(80);
s.add(99);
Iterator it=s.iterator();
while(it.hasNext())
System.out.println(it.next());
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.
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.
package Collection;
import java.util.Iterator;
import java.util.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();
while (iterator.hasNext()) {
OutPut:-
Java faqs
This section contains collection of frequently asked questions(faqs) in interview or viva of Java.
Ans:
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.
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.
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.
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 entire caching mechanism are redesigned and consolidated between Java Web Start and Java Plug-in. This include some
new features in Java Web Start:
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);
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.
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){}
}
}
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.
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>
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.
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.
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.
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.
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.
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){}
}
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
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.
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.
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.
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.
The following diagrams shows the framework of core collection interfaces hierarchy.
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:
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.
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
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:
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:
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.
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.
import java.util.*;
import java.net.*;
Enumeration<NetworkInterface> netis=
NetworkInterface.getNetworkInterfaces();
while(netis.hasMoreElements())
NetworkInterface nis=netis.nextElement();
+nis.getName());
+nis.getDisplayName());
+nis.isUp());
+nis.isLoopback());
+nis.getMTU());
+nis.isVirtual());
+nis.getParent());
byte[] haddress=nis.getHardwareAddress();
if (haddress!= null)
System.out.println();
List<InterfaceAddress> iaddress=nis.getInterfaceAddresses();
Iterator<InterfaceAddress> iiaddress=iaddress.iterator();
while(iiaddress.hasNext())
InterfaceAddress iadd=iiaddress.next();
+iadd.getAddress());
+iadd.getBroadcast());
+iadd.getNetworkPrefixLength());
System.out.println();
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
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.
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.
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.
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.
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.
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;
Console c = System.console();
if (c == null) {
System.exit(1);
if (check(login, oldPass)) {
boolean flag;
do {
char [] newPass1 =
char [] newPass2 =
if (flag) {
} else {
change(newPass1);
} while (flag);
}
//check method.
return true;
//change method.
oldPass=password;
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 FileMethod() {
System.out.println("C:");
System.out.println("\nC:\\windows (exist)");
new FileMethod();
C:\windows (exist)
Total Space:
10238640128
Free Space:
6918594560
Usable Space:
6918594560
C:\j2se6>
Download this example.
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.
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.
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.
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.
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.
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.*;
Console c=System.console();
if(c==null)
System.exit(1);
dqname.add(name);
show(dqname);
dqname.addFirst(name);
show(dqname);
dqname.addLast(name);
show(dqname);
dqname.offerFirst(name);
show(dqname);
dqname.offerLast(name);
show(dqname);
by using getFirst()");
String str1=dqname.getFirst();
getLast()");
str1=dqname.getLast();
using peekFirst()");
str1=dqname.peekFirst();
using peekLast()");
str1=dqname.peekLast();
by using removeFirst()");
str1=dqname.removeFirst();
show(dqname);
by using removeLast()");
str1=dqname.removeLast();
show(dqname);
by using pollFirst()");
str1=dqname.pollFirst();
show(dqname);
by using pollFirst()");
str1=dqname.pollLast();
show(dqname);
while(nameIter.hasNext())
System.out.println(nameIter.next());
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
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.
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!
C:\vinod\collection>
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.
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!
Remove element: 10
Now navigable set: [100, 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.
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 is empty
C:\vinod\collection>
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.
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>
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.
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");
+ tMap.get(tMap.firstKey()) + "\n");
+ tMap.get(tMap.lastKey()) + "\n");
+ tMap.remove(tMap.firstKey()));
+ tMap.values() + "\n");
+ tMap.remove(tMap.lastKey()));
C:\vinod\collection>javac TreeMapExample.java
C:\vinod\collection>java TreeMapExample
Tree Map Example!
C:\vinod\collection>
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.
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!
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
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
8. Java IO improvements
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
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 {
Iterator<Integer> it = myList.iterator();
while(it.hasNext()){
Integer i = it.next();
System.out.println("Iterator Value::"+i);
myList.forEach(new Consumer<Integer>() {
});
myList.forEach(action);
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.
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
package com.journaldev.java8.defaultmethod;
@FunctionalInterface
System.out.println("I1 logging::"+str);
System.out.println("Printing "+str);
// }
package com.journaldev.java8.defaultmethod;
@FunctionalInterface
void method2();
System.out.println("I2 logging::"+str);
Notice that both the interfaces have a common method log() with implementation logic.
package com.journaldev.java8.defaultmethod;
@Override
@Override
@Override
System.out.println("MyClass logging::"+str);
Interface1.print("abc");
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.
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.
@Override
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:
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.
package com.journaldev.java8.stream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
//sequential stream
If you will run above example code, you will get output like this:
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.
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.
Map replaceAll(), compute(), merge() methods.
Java IO improvements
Some IO improvements known to me are:
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.
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
Reply
2. Ravi Gupta says
Reply
3. vellai varanan says
MAY 24, 2018 AT 9:08 PM
thanks m pankaj
Reply
4. Meghala Devi says
Reply
5. Md. Ahsan Kabir says
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
Pankaj says
Reply
7. Ashish Balani says
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
interface MyFunctionalInterface
{
System.out.println(“Static method2 implementation”);
/**
* So no overriding .
* */
{
System.out.println(“Static method2 implementation”);
}
public static void main(String[] args) {
MyFunctionalInterface.method2();
@Override
return 0;
The methods can be called with Interface name not implementation object reference or implementation class name
Overriding not applicable for interface static method as it is not available by default to implementation class
Reply
9. Mridula says
4. Improved Security
Reply
Reply
12. Abdulaziz says
Nice and easy-to-follow article about main java 8 features. Thank you.
Reply
people wrote entire books about why lambda expressions are elegant and useful
Pankaj says
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
Rahul kumar says
Lambda expression allowed us functional programming rather than reduces the code.
“System.out.println vs System.out::println.”
Reply
14. Mithila says
Reply
15. Thirupathi says
Reply
Reply
Thanxxxxxxxxxxx Pankaj ,
Reply
Thanks a lot Pankaj. A very concise and self explanatory info and that too at a one place. 🙂
Reply
Pankaj says
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
It’s good to know but it’s just to reduce number of lines of code.
Reply
20. Tomasz Krzysztof says
Thank you!
Reply
21. Valentino says
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
Reply
22. Rama says
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
Reply
Very helpful. I’m very grateful to see such topics discussed here.
Reply
Reply
Simply superb
Reply
It’s very useful to know overview of new features of Java 8 in less time.
Reply
28. jdk1.7 says
Is it me or these new features are turning the language into unreadable mess
Reply
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 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
Reply
Anand says
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
Reply
31. krishna says
interface MyInt2{
f.log();
@Override
public void log() {
MyInt1.super.log();
Reply
kammiti krishna says
32. Bharath says
Good explanation
Reply
33. Rajesh says
Nice tutorial.
Reply
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
35. Dhanya says
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
Reply
Reply
Debendra Dhinda says
SEPTEMBER 6, 2016 AT 9:10 AM
A beautiful Updation
Reply
38. neha says
great tutorial
Reply
Reply
40. Venkat says
Simply superb!!!
Reply
41. hitesh says
JULY 13, 2016 AT 12:22 AM
Reply
42. Manoj says
Good Article
Reply
43. ganesan says
JUNE 13, 2016 AT 5:07 PM
very nice
Reply
Nice article
Reply
Reply
Reply
47. Ravi says
JANUARY 25, 2016 AT 8:36 PM
Reply
48. prabhath says
Thanks a lot.
Reply
49. dhrumil says
listOfPrimes.stream().forEach(System.out::println);
// let’s do something to each element before printing
Reply
50. Prabu says
can you explain little more about FuctionalInterface and functional programming
2.what is functional Interface and what purpose it has been introduced in java and what we can achieve with
functional Interface
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
Reply
53. Tayyab says
DECEMBER 30, 2014 AT 5:28 AM
Reply
Nice article.. You explained really well.. Thanks and keep it up..
Reply
Really Nice & very useful stuff, But need to provide the examples for the 6 and 7th features.
Reply
Pankaj says
I have already listed the important new methods in the Collection and Concurrency APIs with brief explanation, just
Reply
56. Rajiv says
Reply
57. Sathy\narayanan says
Very good stuff man, really i’m very happy that i gained many things in java from you!!!
Reply
sifun nanda says
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 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.
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");
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.
Output:
Hello
Output:
27
Output:
We can iterate Maps and other collection classes using lambda expression, refer this guide: Iterating Map and List using
lambda expression
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:
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).
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:
Output:
Aditya
Jon
Lucy
Negan
Rick
Sansa
Steve
Output:
Hello World!
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.
Output:
Result: 112
}
}
Output:
Result: 112
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);
});
add(button);
}
public static void main(String args[])
{
new Example();
}
}
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);
add(button);
}
public static void main(String args[])
{
new Example();
}
}
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.
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.
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();
}
}
Output:
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");
}
}
}
Output:
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.
interface MyInterface{
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.
interface MyInterface{
}
}
Output:
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.
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:
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");
}
}
Output:
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.
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.
Output:
3
6
9
12
15
18
//creating two streams from the two lists and concatenating them into one
Stream<String> opstream = Stream.concat(alphabets.stream(), names.stream());
Output:
Related Posts:
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.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class Example {
public static void main(String[] args) {
Output:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
longnames.forEach(System.out::println);
Output:
Melisandre
Daenerys
Joffery
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Example {
longnames.forEach(System.out::println);
Output:
Joffery
Output:
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);
}
});
}
}
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
fruits.forEach(System.out::println);
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
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));
Output:
References:
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
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
List<String> names =
Arrays.asList("Jon", "Ajeet", "Steve",
"Ajeet", "Jon", "Ajeet");
System.out.println(map);
}
}
Output:
Output:
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
Output:
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.
import java.util.StringJoiner;
public class Example {
public static void main(String[] args) {
// Passing Hyphen(-) as delimiter
StringJoiner mystring = new StringJoiner("-");
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(",", "(", ")");
Output:
(Negan,Rick,Maggie,Daryl)
mystring.add("Negan");
mystring.add("Rick");
mystring.add("Maggie");
mystring.add("Daryl");
myanotherstring.add("Sansa");
myanotherstring.add("Imp");
myanotherstring.add("Jon");
myanotherstring.add("Ned");
Output:
In the above examples, we have seen the add() and merge() methods of StringJoiner class. Lets see the other methods of this
class.
Output:
References:
Java 8 – StringJoiner JavaDoc
Java 8 Optional Class
BY CHAITANYA SINGH | FILED UNDER: JAVA 8 FEATURES
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.
Output:
Output:
Output:
//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
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:
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.
Output:
1 5 19 22 32 89
References:
Java 8 – Parallel Sort JavaDoc
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