Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies

Wednesday, June 17, 2015

Thinking Like An App Designer

There’s more to designing mobile apps than meets the eye. The task requires a deep knowledge of devices, and it often means changing the way we think — even if that means leaving behind much of what we’ve learned from designing for the web.
I started my career like many designers: working on print design projects. Shortly thereafter, I discovered the world of websites, which fascinated me and became the focus of my work for some time. Along the way I learned concepts related to interaction design and user experience, which I hardly knew existed until then.
At some point I felt stuck in a kind of repetitive work cycle: I had found a formula, an almost surefire way of designing, that enabled me to deliver each new project more easily and quickly than ever before, but in some way or another, all of the designs looked similar. It was then that the first versions of iOS and Android were released.
Thereafter, looking for a breath of fresh air, my life took an unexpected turn, focusing me on something that seemed completely different: mobile app design. That was what I needed, a real challenge. I not only had to learn new things, but somehow had to forget part of that magical recipe for designing websites that I had been using till then.
A few years after that aha moment, just days ago in fact, the design community met the launch of new apps for Apple’s smartwatch with mixed emotions. On the one hand, seeing a device that offers a world of new design possibilities is exciting. On the other, the challenge of understanding a medium with unprecedented interactions and use cases is daunting.
It’s not the first time we’ve seen a device like this on the market. But as new technologies that require new design approaches appear more and more frequently, we will have to adapt at an increasingly quicker rate.

Of course, the first big push came nearly 20 years ago, with ubiquitous Internet access, which ushered in the first websites. Before then, most designers, like me, focused on print, and the arrival of the Internet required us to learn how to design for an interactive medium. The user had become much more than just a spectator.
The transition was harder for some than for others, and that’s why so many websites of the time looked like signs with buttons on them — designers didn’t immediately understand the characteristics of this new medium.

The same thing is happening today with apps. One often comes across applications that look like mini-websites: They’re constructed as web pages “translated” for smartphones, and in turn, they fail with contrast, font size, touch targets and gestures. They also miss the mark with who will be using the app, where and on what devices.
When designing for mobile, escaping from a web structure is imperative because it can work against us. We have to face projects with a different mentality and fully comprehend the mobile devices in order to take full advantage of them and deliver delightful experiences.
So, what do you need in order to be an app designer? Beyond knowledge and tools, you need to change the way you think. Below are a few recommendations for adapting to the world of app design.

Change The Way You Work

Hundreds of apps are entering the market at this very moment — you’ve got no time to lose.
As professionals, we can no longer afford to spend weeks or months on detailed fancy designs before launching a product, only then to realize that other apps have already solved the problem (and most likely solved it in a similar way).
This is where lean UX comes in, a way of working in short quick cycles. The approach entails continual iteration on design and development, keeping one single focus in mind: that nothing is certain until users try it out.

Thus, app design can’t begin with interface design in Photoshop or Illustrator. It has to start before that, with wireframe-based prototypes and basic designs. That way, if change is necessary, it will take moments — not months — to apply.
Beginning with the visual design is a normal tendency for designers: That’s the stage that is usually most interesting to us. In some way, we also got used to working in this way because it was the only way possible.
Recently, in speaking with many designers, most look at me with surprise when I recommend that they start working on projects without even using the computer, but instead by simply drawing on paper. It sounds so natural that we often forget it’s even a possibility. Designing like this has proven to be very useful in preventing us from thinking in terms of variables (such as the size of the design document, colors and fonts used, etc.) — variables and details that can actually block our creativity when we are starting a project.
Personally, I find sketching on paper to be much more useful because we focus only on the idea and the problem to be solved, without falling into the trap of considering design details, or at least not in that first stage.
Mobile first,” or starting with the small screen, is also a good strategy to employ. Even if your app will run on both smartphones and tablets, beginning by designing for the smaller phone is more effective. Starting the design process from a mobile standpoint forces us to prioritize, choose and above all alter our mental structure, which is accustomed to the larger screen of a desktop computer as a general point of departure.

The first time I started a project this way, I almost ended up with a headache. Perhaps it’s a similar situation when you go to the gym for the first time; muscles that you haven’t used for a while start to hurt, due to the effort of working differently. If you haven’t done it yet, try it some day. You’ll notice how your priorities change, and you will sooner realize what are the truly important things in your app, the things that are indispensable.
You could also draw a parallel with travelling with luggage. If you have a small suitcase, what should you bring? You’d bring the most important things, of course, the things you are sure to need during the trip, and leave everything else behind. Believe it or not, this ordinary example is similar to what happens when we design for a smartphone.

Learn From The Other Half

The success of an app depends on both the designer and the developer, who must work together to innovate and achieve the highest level of quality. To accomplish this while working efficiently, you can shorten iterations by working in parallel. For this to work, you must both be conscious of the complexities of the design as well as of the actual implementation.
One way to do this is to learn to use development tools, not necessarily to develop apps from start to finish, but at least to build screens that can be transferred quickly and faithfully, while accurately communicating the design’s intent.

Shortly after arriving in Barcelona, I started working at a tech startup. I was surprised to find that I was the sole designer there — I was literally surrounded by developers, and at first there were a lot of bottlenecks because everybody was waiting for me to finish my design work in order to continue their own.
With time, I learned how to use tools such as Xcode and some basic programming languages. These enabled me to make more complex proposals and to work at certain moments at the same pace as the rest of the team.
After a while, once I had been with the company for months, developers learned the way I work, too. They would now open my design documents directly and would know how to export design assets without my help.
Finally, I would like to teach you a little trick: Learn to use the same terminology as the rest of the team. Doing so, you will feel that everybody in the office speaks the same language. Designers and developers often refer to the same thing but in different words, which makes understanding between parties more difficult.

Recognize The Value Of Teamwork

Going back a bit to the previous topic, teamwork goes far beyond sharing office space. It entails collaboration between roles and constant communication. Lean app design entails putting an end to cascading processes, where the work of one individual begins where another one’s ends.
But in practice, most teams have settled into an efficient hybrid process, with developers following an agile methodology (working with a goal to accomplish by a specific deadline) and designers following a lean one (rapid iteration, usually without a specific deadline).
While there is still a vestige of a “cascade” (or waterfall) here, with designers usually working just a bit ahead of the rest of the team, developers can certainly start without waiting for every design to be ready.
That’s why an app designer must recognize that their coworkers — especially programmers — are allies, not enemies. Understanding one another and growing accustomed to working together will lead to a better, more synergetic result.
We are often afraid to share our work. We tend to be somewhat defensive of the reviews and comments that may arise, especially coming from fellow designers. The truth is that many of the things that others say are vital to improving our proposals, including feedback from those who do not have a design background, such as programmers. Their vision, generally more pragmatic than ours, can provide a good balance.
People in a company I visited a while ago told me that designers and developers work on separate floors, communicating through various systems of instant messaging. I suggested that they try something else: Designers and developers who work on the same projects should try sitting all mixed together. A few months after that, they told me that the quality of their products had dramatically improved, as did even the relationships between team members.

Use Various Operating Systems

When you’re designing a mobile app, you can’t just use your own phone for reference. If your target is the global mobile market, you’ve got to have access to at least Android, iOS and Windows Phone devices and grow accustomed to using them constantly in order to fully understand how to resolve different design scenarios on each platform.
The truth is that the world doesn’t begin and end with the iPhone. So many designers limit themselves to iOS, and when the time comes to design for Android, they just translate — often almost literally — the original app.

Interaction patterns (i.e. established solutions to problems of design) are different on each operating system. As such, designers must alternate frequently in order to assimilate them and use them correctly.
To name just a few examples, the location of tabs, how to show menus, and when and how to display primary and secondary actions vary on each of these mobile operating systems.
To learn the different patterns on each mobile OS, here’s a practical exercise you can follow: Download and install the same app on various operating systems, and analyze their distinctions and similarities critically; the patterns should be different. So, if you find that an app looks and works practically the same on iOS and Android, it’s possible that something has not been done correctly on one of them.

Moreover, continually looking at and trying out other applications is a great way to discover how to solve your own interface problems. For example, many times when I feel some sort of a creative block and don’t know how to fix a problem, I’ll start playing with my phone, carefully analyzing the apps to see their approach to the problem I’m facing.
If you don’t have a phone near you, you could check websites such as Pttrns (for iPhone), Android App Patterns and Windows Phone UI Design Patterns, which have plenty of examples that might be useful to you.

Prototype Everything

An agile methodology requires understanding how something will look and function prior to implementation. Likewise, prototypes help us to evaluate (via user testing) an app’s usability. Ideally, we would not have to wait long before building our first prototype.

Few of us probably remember the Palm Pilot: One of the first prototypes was a simple piece of wood with a sheet of paper on it with the printed design of the interface. Employees would carry the prototype in their pockets as if it were a real device.
For what it was intended to test — size, weight and comfort of use — that prototype was more than enough. The point is to determine the extent to which it’s necessary to design in order to test what you have in mind, and then get down to work!
Numerous tools exist for prototyping and even viewing a design on smartphones as though it were a finished product. That being said, a prototype has to do more than just show a static design; it must also include images, transitions and gestures.

Choosing the most appropriate tool will depend a lot on your workflow, what you want to achieve and the result you are expecting. For example, I often use POP when I have no more than simple wireframes drawn on paper. With this app, I can take pictures of designs, then add gestures and transitions — quickly and easily!
But when a concept is more advanced, I find it more convenient to work in design-specific software, such as Sketch, and then build a prototype using Marvel, Flinto or InVision, making for a more polished prototype. (Note that sometimes one tool is not necessarily better than another. Choosing among them will partly depend on which you feel most comfortable with. However, if you’d like to learn more about prototyping with Sketch and InVision specifically, Smashing Magazine has you covered!)
As mentioned, a ton of prototyping apps are out there, so many that I decided a few months ago to create a small website, Prototyping Tools, that lists all of them that I am aware of. The website provides an overview of which features each tool provides and so should help you choose one.

On the other hand, be aware that operating systems like Android — with its “material design” — are bringing more focus to micro-interactions. Prototyping micro-interactions is the responsibility of many designers today. (A tool like Keynote enables you to prototype these kinds of details with relative ease. Keynote’s Magic Move option comes in handy here.)

Don’t Trust What You See

When designing for the web, it’s possible to watch a design come to life as you work. But with apps, you have to test on a mobile device in order to see how an interface will look (and function). Above all, such testing is imperative for choosing contrast and sizes.
Tools for both Android and iOS will help designers view their work on mobile screens with varying resolutions and densities. For iOS, one of the most well-known options is LiveView. Another, the one I use most, is Skala (available for both iOS and Android), which comes with a desktop version that you can use on a Mac. If you use Sketch, you could also try Sketch Mirror.
Unfortunately, a tool of this kind is not available for Windows and Windows Phone (at least not that I’m aware of).

In my workflow, I always preview a design on my phone to be sure of how it will look before taking the next step. Likewise, I usually start designing for one operating system at a time, and always with the phone close to me most of the time. That way, I can frequently review how my work will appear on that screen, and from the moment the first wireframes are ready, I can be sure that the sizes (of graphics, text and touch targets), contrast and colors will be the ones I’m expecting. If you don’t do this, you might notice it later, when making changes and corrections would require much more time.
Also important, start working with a design document that is the same size (in width and height) as the phone on which you are previewing your work. (Note: If you are designing for different screen sizes, then keep in mind that pixels are no longer the best way to measure sizes, because they change from one OS to another — for example, see the difference between points on iOS and density-independent pixels on Android. This forces you in some way to fully understand the differences in how to design and how to treat images in the current mobile landscape.)
Once your designs have been implemented by the developers, check how the app looks and performs on different phones and OS versions, and not only in the best phone you have next to you.

Design Humbly

App designers must abandon the concept of creating something final. An app is never finished, because it’s a digital product that evolves over time. For this very reason, we can’t approach interface design with a definitive stance. The truth is discovered through usability testing and deciphering what problems users encounter.
Sometimes we designers tend to think that when a user makes a mistake using an app, they are at fault, thus freeing us from all liability. The truth is that we more likely have done something wrong.
Detecting problems (and discovering our mistakes) isn’t a bad thing. Rather, it is an opportunity to learn and correct our work, thereby improving it and building something that’s easier to use. We must approach design with an attitude of humility.
In one company where I worked, every time I told my boss that I had finished a design, he would ask me, “Have you tested it with users already?” I hadn’t always tested it yet, but in the end I incorporated it as a habit, and each time I tested, I went in ready with an open mind, willing to see what problems I would find.
This can only be done if you are mature enough to accept your mistakes and learn from them. It’s difficult, but if you succeed it’s really worth it.

Stay At The Forefront

The amount of information out there makes it nearly impossible to stay current on everything when designing for tomorrow. Nevertheless, as app designers, we must stay engaged and curious about what’s new and what’s to come.
This includes trends in app design, as well as new versions of operating systems. Like it or not, we have to install new operating systems and stay ahead of the curve in order to see where app design is headed.
One good way to get valuable design information is by reading official design guides for the latest OS versions. You can also learn from industry leaders, like Josh Clark and Luke Wroblewski, to name just a couple.
Staying on top of things also means trying tools that simplify design and make our work more efficient as they come onto the market. We can’t be afraid of getting out of our comfort zone and abandoning our old ways of working and designing.

Along these lines, a while ago I finally dared to use Sketch. It was a bit hard at first, because it meant learning something new from scratch, when — I have to admit — I was already comfortable (sort of) using the tools I already knew.
A few months later, I now realize that this software has quite a gentle learning curve. It saves me time and enables me to work in a very agile manner — and all of that has been a reward for being willing to learn something new.

Conclusion

At the end of the day, changing one’s mindset to adapt to apps comes from the inside. No one will force you to do it. If you don’t adjust, you run the risk of becoming little more than an icon factory, just a small step in a larger process of design.
Above all, designing apps requires a new way of thinking. It’s time to leave our web design boxes and to understand smartphones, tablets and even watches as separate and distinct devices. It’s the only way to truly design complete, comprehensive mobile experiences.

Additional Resources

Wednesday, June 3, 2015

SSI (Server Side Includes) in Servlet

  Server Side Includes  are commands and directives placed in the web page that can be evaluated by the web server when the web page being served. The servlet code embedded inside the HTML code called as SSI.
           SSI cant be supported for all web server. so you can read web server supported documents before using the SSI in your code.
           It helpful for when you want to small part of page loading dynamically instead of whole page loading. Below the Syntex given,


<SERVLET CODE=MyservletClassname CODEPASE=path      initparam1=initparamvalue initparam2=initparam2value>

<PARAM NAME=name1 VALUE=value1>

<PARAM NAME=name2 VALUE=value2>

</SERVLET>


Here the path indicate the MyservletClassname class name path in the server.  you can setup the remote file path also. the remote file path syntex is,

http://server:port/dir


Note: If the above text show in the HTML page means the web server not support the <SERVLET> tag.

You can pass the any no of PARAM in that SERVLET. It can be accessed by using getParameter() method in ServletRequest class.

You can save the SSI contains html file using .shtml extension.



Program for SSI :-

The Example can be showing the current time for here and the time in London and Newyork.

First to write the the shtml file to call the servlet class.

<HTML>
<HEAD><TITLE>Times!</TITLE></HEAD>
<BODY>
The current time here is:
<!-- here the ssi servlet class has been called-->
<SERVLET CODE=CurrentTime>
</SERVLET>
<P>
The current time in London is:
<!-- here the ssi servlet class has been called and send the parameter-->
<SERVLET CODE=CurrentTime>
<PARAM NAME=zone VALUE=GMT>
</SERVLET>
<P>
And the current time in New York is:
<!-- here the ssi servlet class has been called and send the parameter-->
<SERVLET CODE=CurrentTime>
<PARAM NAME=zone VALUE=EST>
</SERVLET>
<P>
</BODY>
</HTML>

After that the web server receive the SERVLET tag and process the SSI. First it search the server container has the SSI servlet class i.e .shtml file has the CODE attribute value as treated as SSI servlet class.

Then the file found it process the SSI servlet. The SSI servlet use either doget() or service() method in request process.
CurrentTime SSI servlet class are given below,

package com.shinnedhawks;

import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 * Getting date based on time zone
 * @author Ramachandran (ramakavanan@gmail.com)
 */

public class CurrentTime extends HttpServlet {

  public void doGet(HttpServletRequest req, HttpServletResponse res)
                               throws ServletException, IOException {

    PrintWriter out = res.getWriter();

    Date date = new Date();
    DateFormat df = DateFormat.getInstance();

    // Here receive the request param from .shtml file
    String zone = req.getParameter("zone");
    if (zone != null) {
      TimeZone tz = TimeZone.getTimeZone(zone);
      df.setTimeZone(tz);
    }

    // Here write the response shtml file
    out.println(df.format(date));
  }
}

This SSI servlet we can change the printwriter class initialization in the following way also to write the response in that .shtml file,

PrintWrite out= new PrintWriter(res.getOutputStream(), true);


This out put will be shown in browser that replace  the SERVLET tag and write the response return form the SSI servlet class,

For example output is,
    The current time here is: 6/5/15 1:00 PM
    The current time in London is: 6/6/15 1:00 AM
    And the current time in New York is: 6/5/15 9:00 PM

Monday, June 1, 2015

Java Collection Tutorial

 

Java Collection Framework

         The java collections are one of the core framework of java. The collections are most widely used by the programmers. This collections used to write more efficient and reusable codes , And also most of experienced interview questions are from the java collections only.

  1. What is Java Collections ?
  2. Java Collections Interfaces
  3. Traversing Collections
  4. Java Collection Classes
  5. Collections class
  6. Synchronized Wrappers
  7. Unmodifiable wrappers
  8. Thread Safe Collection
  9. Collections API Algorithms
  10. Java 8 Collections API Features
  11. Collection classes in a Nutshell

What is Java Collections Framework?

Collections are like containers that groups multiple items in a single unit. For example; a collection of cards, list of names etc. Collections are used to store, retrieve, manipulate, and communicate aggregate data.Collections are used almost in every programming language and when Java arrived, it also came with few Collection classes; VectorStackHashtableArray. Java 1.2 provided Collections Framework that is architecture to represent and manipulate Collections in a standard way. Java Collections Framework consists of following parts:
  • Interfaces: Java Collections Framework interfaces provides the abstract data type to represent collection. java.util.Collection is the root interface of Collections Framework. It is on the top of Collections framework hierarchy. It contains some important methods such as size(), iterator(),add(), remove(), clear() that every Collection class must implement. Some other important interfaces are  java.util.List, java.util.Set, java.util.Queue  and  java.util.Map.  
  • Implementation Classes: Java provides core implementation classes for collections. We can use them to create different types of collections in our program. Some important collection classes are ArrayList,  LinkedList,  HashMap,  HashSetTreeSet.These classes solve most of our programming needs but if we need some special collection class, we can extend them to create our custom collection class.                                                               Java 1.5 came up with thread-safe collection classes that allowed to modify Collections while iterating over it, some of them are  CopyOnWriteArrayList,  ConcurrentHashMap,  CopyOnWriteArraySet . These classes are in java.util.concurrent package. All the collection classes are present in java.util andjava.util.concurrent package.
  • Algorithms: Algorithms are useful methods to provide some common functionalities, for example searching, sorting and shuffling.
Note :  Map is the only interface that does not  inherits from Collection interface but it is part of Collections framework. All the collections framework interfaces are present in java.util  packages.

Benefits of Java Collections Framework
Java Collections framework have following benefits:
  • Reduced Development Effort – It comes with almost all common types of collections and useful methods to iterate and manipulate the data. So we can concentrate more on business logic rather than designing our collection APIs.
  • Increased Quality – Using core collection classes that are well tested increases our program quality rather than using any home developed data structure.
  • Reusability and Interoperability
  • Reduce effort – to learn any new API if we use core collection API classes.

Java Collections Interfaces

         Core collection interfaces are the foundation of the Java Collections Framework. Note that all the core collection interfaces are generic; for example public interface Collection<E>. The <E> syntax is for Generics and when we declare Collection, we should use it to specify the type of Object it can contain. It helps in reducing run-time errors by type-checking the Objects at compile-time.

         If an unsupported operation is invoked, a collection implementation throws  an UnsupportedOperationException.

Collection Interface

This is the root of the collection hierarchy. A collection represents a group of objects known as its elements. The Java platform doesn’t provide any direct implementations of this interface.
The interface has methods to tell you how many elements are in the collection (sizeisEmpty), to check whether a given object is in the collection (contains), to add and remove an element from the collection (addremove), and to provide an iterator over the collection (iterator).
Collection interface also provides bulk operations methods that work on entire collection – containsAll,addAllremoveAllretainAllclear.
The toArray methods are provided as a bridge between collections and older APIs that expect arrays on input.
Note : In JDK 8 and later the Collection interface also exposes methods stream() and parallelStream() for obtaining sequential or parallel streams from the underlying collection.

Iterator Interface
Iterator interface provides methods to iterate over any Collection. We can get iterator instance from a Collection using iterator method. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators allow the caller to remove elements from the underlying collection during the iteration. 
Iterator comes inside the java.util package. It contains the three methods to implement over the collections. They are hasNext(), next(), remove().

Set Interface
Set is a collection that cannot contain duplicate elements. This interface models the mathematical set abstraction and is used to represent sets, such as the deck of cards.
The Java platform contains three general-purpose Set implementations: HashSetTreeSetEnumSetand LinkedHashSet. Set interface doesn’t allow random-access to an element in the Collection. You can use iterator or foreach loop to traverse the elements of a Set.

Example: for creating a set instance
Set setA = new EnumSet();
Set setB = new HashSet();
Set setC = new LinkedHashSet();
Set setD = new TreeSet()

List Interface

List is an ordered collection and can contain duplicate elements. You can access any element from it’s index. List is more like array with dynamic length. List is one of the most used Collection type. ArrayList, LinkedList, Vector and Stack are implementation classes of List interface.
List interface provides useful methods to add an element at specific index, remove/replace element based on index and to get a sub-list using index.

Example: for creating a List instance
List listA = new ArrayList();
List listB = new LinkedList();
List listC = new Vector();
List listD = new Stack();   
Note : Collections class provide some useful algorithm for List – sort,  shuffle,  reverse,  binarySearch  etc.

Queue Interface

Queue is a collection used to hold multiple elements prior to processing. Besides basic Collection operations, a Queue provides additional insertion, extraction, and inspection operations.
Queues typically, but do not necessarily, order elements in a FIFO (first-in, first-out) manner. Among the exceptions are priority queues, which order elements according to a supplied comparator or the elements’ natural ordering. Whatever the ordering used, the head of the queue is the element that would be removed by a call to remove or poll. In a FIFO queue, all new elements are inserted at the tail of the queue.

LinkedList and PriorityQueue  are implementation classes of Queue interface.

Example : for creating a queue instances,
Queue queueA = new LinkedList();
Queue queueB = new PriorityQueue();

Dequeue Interface

A linear collection that supports element insertion and removal at both ends. The name deque is short for “double ended queue” and is usually pronounced “deck”. Most Deque implementations place no fixed limits on the number of elements they may contain, but this interface supports capacity-restricted deques as well as those with no fixed size limit.
This interface defines methods to access the elements at both ends of the deque. Methods are provided to insert, remove, and examine the element.

LinkedList and ArrayDeque  are implementation classes of Dequeue interface.

Example: for creating a dequeue instances,

Deque dequeA = new LinkedList();
Deque dequeB = new ArrayDeque();

Map Interface

A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value.
The Java platform contains three general-purpose Map implementations:  HashMapTreeMapEnumMap, IdentityHashMap, Properties, HashTable, WeakHashMap and LinkedHashMap.
The basic operations of Map are putgetcontainsKeycontainsValuesize, and isEmpty.
Example:
Map mapA = new HashMap();

mapA.put("key1", "element 1");
mapA.put("key2", "element 2");
mapA.put("key3", "element 3");

ListIterator Interface

An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator’s current position in the list.
A ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next().

SortedSet Interface

SortedSet is a Set that maintains its elements in ascending order. Several additional operations are provided to take advantage of the ordering. Sorted sets are used for naturally ordered sets, such as word lists and membership rolls.

Example :
SortedSet setA = new TreeSet();

Comparator comparator = new MyComparator();
SortedSet setB = new TreeSet(comparator);

SortedMap Interface

Map that maintains its mappings in ascending key order. This is the Map analog of SortedSet. Sorted maps are used for naturally ordered collections of key/value pairs, such as dictionaries and telephone directories.

Example :
SortedMap mapA = new TreeMap();

Comparator comparator = new MyComparator();
SortedMap mapB = new TreeMap(comparator);

Traversing Collections

Collection traverse can be done using three ways. 
1. Using aggregate operations
2. Using For-each block
3. Using Iterator s

Java Collection Classes

Java Collections framework comes with many implementation classes for the interfaces. Most common implementations are ArrayList, HashMap and HashSet. Java 1.5 included Concurrent implementations; for example ConcurrentHashMap and CopyOnWriteArrayList. Usually Collection classes are not thread-safe and their iterator is fail-fast. In this section, we will learn about commonly used collection classes.

HashSet Class

This is the basic implementation the Set interface that is backed by a HashMap. It makes no guarantees for iteration order of the set and permits the null element.
This class offers constant time performance for basic operations (addremovecontains and size), assuming the hash function disperses the elements properly among the buckets. We can set the initial capacity and load factor for this collection. The load factor is a measure of how full the hash map is allowed to get before its capacity is automatically increased.

Example:

 HashSet<String> hs = new HashSet<String>();
 //add elements to HashSet
 hs.add("first");
 hs.add("second");
 hs.add("third");
 System.out.println(hs);
 System.out.println("Is HashSet empty? "+hs.isEmpty());
 hs.remove("third");
 System.out.println(hs);
 System.out.println("Size of the HashSet: "+hs.size());
 System.out.println("Does HashSet contains first element? "+hs.contains("first"));

TreeSet Class
NavigableSet implementation based on a TreeMap. The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.
This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).
Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal.

Example :
import java.util.TreeSet;
 
public class MyBasicTreeset {
 
    public static void main(String a[]){
         
        TreeSet<String> ts = new TreeSet<String>();
        ts.add("one");
        ts.add("two");
        ts.add("three");
        System.out.println("Elements: "+ts);
        //check is set empty?
        System.out.println("Is set empty: "+ts.isEmpty());
        //delete all elements from set
        ts.clear();
        System.out.println("Is set empty: "+ts.isEmpty());
        ts.add("one");
        ts.add("two");
        ts.add("three");
        System.out.println("Size of the set: "+ts.size());
        //remove one string
        ts.remove("two");
        System.out.println("Elements: "+ts);
    }
}

ArrayList Class
Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector, except that it is unsynchronized.)
The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.
Example:
import java.util.ArrayList;
 
public class MyBasicArrayList {
 
    public static void main(String[] a){
         
        ArrayList<String> al = new ArrayList<String>();
        //add elements to the ArrayList
        al.add("JAVA");
        al.add("C++");
        al.add("PERL");
        al.add("PHP");
        System.out.println(al);
        //get elements by index
        System.out.println("Element at index 1: "+al.get(1));
        System.out.println("Does list contains JAVA? "+al.contains("JAVA"));
        //add elements at a specific index
        al.add(2,"PLAY");
        System.out.println(al);
        System.out.println("Is arraylist empty? "+al.isEmpty());
        System.out.println("Index of PERL is "+al.indexOf("PERL"));
        System.out.println("Size of the arraylist is: "+al.size());
    }
}

LinkedList Class

Doubly-linked list implementation of the List and Deque interfaces. Implements all optional list operations, and permits all elements (including null).
All of the operations perform as could be expected for a doubly-linked list. Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index.

Example:
import java.util.LinkedList;
 
public class MyBasicOperations {
 
    public static void main(String a[]){
         
        LinkedList<String> ll = new LinkedList<String>();
        ll.add("Orange");
        ll.add("Apple");
        ll.add("Grape");
        ll.add("Banana");
        System.out.println(ll);
        System.out.println("Size of the linked list: "+ll.size());
        System.out.println("Is LinkedList empty? "+ll.isEmpty());
        System.out.println("Does LinkedList contains 'Grape'? "+ll.contains("Grape"));
    }
}

HashMap Class

Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits null. This class makes no guarantees for the order of the map.
This implementation provides constant-time performance for the basic operations (get and put). It provides constructors to set initial capacity and load factor for the collection.
Further Read: HashMap vs ConcurrentHashMap

Example:
public class MyBasicHashMap {
 
    public static void main(String a[]){
        HashMap<String, String> hm = new HashMap<String, String>();
        //add key-value pair to hashmap
        hm.put("first""FIRST INSERTED");
        hm.put("second""SECOND INSERTED");
        hm.put("third","THIRD INSERTED");
        System.out.println(hm);
        //getting value for the given key from hashmap
        System.out.println("Value of second: "+hm.get("second"));
        System.out.println("Is HashMap empty? "+hm.isEmpty());
        hm.remove("third");
        System.out.println(hm);
        System.out.println("Size of the HashMap: "+hm.size());
    }
}

TreeMap Class

A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.
This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations. Algorithms are adaptations of those in Cormen, Leiserson, and Rivest’s Introduction to Algorithms.
Note that the ordering maintained by a tree map, like any sorted map, and whether or not an explicit comparator is provided, must be consistent with equals if this sorted map is to correctly implement the Map interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Map interface is defined in terms of the equals operation, but a sorted map performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal. The behavior of a sorted map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface.

Example:
import java.util.TreeMap;
 
public class MyBasicOperations {
     
    public static void main(String a[]){
        TreeMap<String, String> hm = new TreeMap<String, String>();
        //add key-value pair to TreeMap
        hm.put("first""FIRST INSERTED");
        hm.put("second""SECOND INSERTED");
        hm.put("third","THIRD INSERTED");
        System.out.println(hm);
        //getting value for the given key from TreeMap
        System.out.println("Value of second: "+hm.get("second"));
        System.out.println("Is TreeMap empty? "+hm.isEmpty());
        hm.remove("third");
        System.out.println(hm);
        System.out.println("Size of the TreeMap: "+hm.size());
    }
}

PriorityQueue Class

Queue processes it’s elements in FIFO order but sometimes we want elements to be processed based on their priority. We can use PriorityQueue in this case and we need to provide a Comparator implementation while instantiation the PriorityQueue. PriorityQueue doesn’t allow null values and it’s unbounded. For more details about this, please head over to Java Priority Queue where you can check it’s usage with a sample program.

Collections class

This class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, “wrappers”, which return a new collection backed by a specified collection, and a few other odds and ends.
This class contains methods for collection framework algorithms, such as binary search, sorting, shuffling, reverse etc.

Synchronized Wrappers

The synchronization wrappers add automatic synchronization (thread-safety) to an arbitrary collection. Each of the six core collection interfaces — Collection, Set, List, Map, SortedSet, and SortedMap — has one static factory method.

public static  Collection synchronizedCollection(Collection c);
public static  Set synchronizedSet(Set s);
public static  List synchronizedList(List list);
public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m);
public static  SortedSet synchronizedSortedSet(SortedSet s);
public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m);
Each of these methods returns a synchronized (thread-safe) Collection backed up by the specified collection.

Unmodifiable wrappers

Unmodifiable wrappers take away the ability to modify the collection by intercepting all the operations that would modify the collection and throwing an UnsupportedOperationException. It’s main usage are;
  • To make a collection immutable once it has been built. In this case, it’s good practice not to maintain a reference to the backing collection. This absolutely guarantees immutability.
  • To allow certain clients read-only access to your data structures. You keep a reference to the backing collection but hand out a reference to the wrapper. In this way, clients can look but not modify, while you maintain full access.
These methods are;
public static  Collection unmodifiableCollection(Collection<? extends T> c);
public static  Set unmodifiableSet(Set<? extends T> s);
public static  List unmodifiableList(List<? extends T> list);
public static <K,V> Map<K, V> unmodifiableMap(Map<? extends K, ? extends V> m);
public static  SortedSet unmodifiableSortedSet(SortedSet<? extends T> s);
public static <K,V> SortedMap<K, V> unmodifiableSortedMap(SortedMap<K, ? extends V> m);

Thread Safe Collections

Java 1.5 Concurrent package (java.util.concurrent) contains thread-safe collection classes that allow collections to be modified while iterating. By design iterator is fail-fast and throws ConcurrentModificationException. Some of these classes are CopyOnWriteArrayListConcurrentHashMap,CopyOnWriteArraySet.
Read these posts to learn about them in more detail.

Collections API Algorithms

Java Collections Framework provides algorithm implementations that are commonly used such as sorting and searching. Collections class contain these method implementations. Most of these algorithms work on List but some of them are applicable for all kinds of collections.

Sorting

The sort algorithm reorders a List so that its elements are in ascending order according to an ordering relationship. Two forms of the operation are provided. The simple form takes a List and sorts it according to its elements’ natural ordering. The second form of sort takes a Comparator in addition to a List and sorts the elements with the Comparator.

Shuffling

The shuffle algorithm destroys any trace of order that may have been present in a List. That is, this algorithm reorders the List based on input from a source of randomness such that all possible permutations occur with equal likelihood, assuming a fair source of randomness. This algorithm is useful in implementing games of chance.

Searching

The binarySearch algorithm searches for a specified element in a sorted List. This algorithm has two forms. The first 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. The second form takes a Comparator in addition to the List and the search key, and assumes that the List is sorted into ascending order according to the specified Comparator. The sort algorithm can be used to sort the List prior to calling binarySearch.

Composition

The frequency and disjoint algorithms test some aspect of the composition of one or more Collections.
  • frequency: counts the number of times the specified element occurs in the specified collection
  • disjoint: determines whether two Collections are disjoint; that is, whether they contain no elements in common

Min and Max values

The min and the max algorithms return, respectively, the minimum and maximum element contained in a specified Collection. Both of these operations come in two forms. The simple form takes only a Collection and returns the minimum (or maximum) element according to the elements’ natural ordering.
The second form takes a Comparator in addition to the Collection and returns the minimum (or maximum) element according to the specified Comparator.

Java 8 Collections API Features

Java 8 biggest changes are related to Collection APIs. Some of the important changes and improvements are:
  1. Introduction of Stream API for sequential as well as parallel processing, you should read Java Stream API Tutorial for more details.
  2. Iterable interface has been extended with forEach() default method for iterating over a collection.
  3. Lambda Expression and Functional interfaces are mostly beneficial with Collection API classes.

Collection classes in a Nutshell

Below table provides basic details of commonly used collection classes.

CollectionOrderingRandom AccessKey-ValueDuplicate ElementsNull ElementThread Safety
ArrayListYesYesNoYesYesNo
LinkedListYesNoNoYesYesNo
HashSetNoNoNoNoYesNo
TreeSetYesNoNoNoNoNo
HashMapNoYesYesNoYesNo
TreeMapYesYesYesNoNoNo
VectorYesYesNoYesYesYes
HashtableNoYesYesNoNoYes
PropertiesNoYesYesNoNoYes
StackYesNoNoYesYesYes
CopyOnWriteArrayListYesYesNoYesYesYes
ConcurrentHashMapNoYesYesNoNoYes
CopyOnWriteArraySetNoNoNoNoYesYes
I hope this tutorial explains most of the topics in java collections framework, please share your opinion with comments.