Tampilkan postingan dengan label java collection tutorial. Tampilkan semua postingan
Tampilkan postingan dengan label java collection tutorial. Tampilkan semua postingan

Minggu, 29 Januari 2017

Though you can use both for loop and enhanced for loop to iterate over arrays and collections like a list, set, or map. There are some key differences between them. In general, enhanced for loop is much more easy to use and less error prone than for loop, where you need to manage the steps manually. At the same time, for loop is much more powerful because you get the opportunity to control over looping process. All the difference, you will learn in this article, stems from this very fact that traditional for loop gives more control that enhanced for loop but on the other hand enhanced or advanced for loop gives more convenience.
Read more �

Senin, 08 Agustus 2016

Suppose you have a ConcurrentHashMap of String and Integer and you want to print all keys and values, how do you that? This is a common, day to day programming task for Java programmer and there are many ways to do it. The Map interface provides several view methods e.g. keySet(), values(), and entrySet() to retrieve all keys, values, and all key and value pairs as entries. You can use respective methods to print all keys, all values, or all key values pairs. For printing, you also have multiple choice e.g. you can either use enhanced for loop or Iterator, though later also provide you the facility to remove key value pairs while printing if needed. Though you should remember that these views are backed by Map, so when you remove a key-value pair from entry set it will also be removed by the ConcurrentHashMap.
Read more �

Sabtu, 21 Mei 2016

Synchronized vs Concurrent Collections
Though both Synchronized and Concurrent Collection classes provide thread-safety, the differences between them comes in performance, scalability and how they achieve thread-safety. Synchronized collections like synchronized HashMap, Hashtable, HashSet, Vector, and synchronized ArrayList are much slower than their concurrent counterparts e.g. ConcurrentHashMap, CopyOnWriteArrayList, and CopyOnWriteHashSet. Main reason for this slowness is locking; synchronized collections locks the whole collection e.g. whole Map or List while concurrent collection never locks the whole Map or List. They achieve thread safety by using advanced and sophisticated techniques like lock stripping. For example, the ConcurrentHashMap divides the whole map into several segments and locks only the relevant segments, which allows multiple threads to access other segments of same ConcurrentHashMap without locking.
Read more �

Rabu, 27 Februari 2013

ConcurrentHashMap in Java is introduced as an alternative of Hashtable in Java 1.5 as part of Java concurrency package. Prior to Java 1.5 if you need a Map implementation, which can be safely used in a concurrent and multi-threaded Java program, then, you only have Hashtable or synchronized Map because HashMap is not thread-safe. With ConcurrentHashMap, now you have a better choice; because not only it can be safely used in the concurrent multi-threaded environment but also provides better performance over Hashtable and synchronizedMap. ConcurrentHashMap performs better than earlier two because it only locks a portion of Map, instead of whole Map, which is the case with Hashtable and synchronized Map. CHM allows concurred read operations and the same time maintains integrity by synchronizing write operations. We have seen basics of ConcurrentHashMap on Top 5 Java Concurrent Collections from JDK 5 and 6 and in this Java tutorial, we will learn:

How ConcurrentHashMap works in Java or how it is implemented in Java.
When to use ConcurrentHashMap in Java
ConcurrentHashMap examples in Java
And some important properties of CHM.
Read more �

Kamis, 07 Februari 2013

Several new Collection classes are added in Java 5 and Java 6 specially concurrent alternatives of standard synchronized ArrayList, Hashtableand synchronized HashMap collection classes. Many Java programmer still not familiar with these new collection classes from java.util.concurrent package and misses a whole new set of functionality which can be utilized to build more scalable and high performance Java application. In this Java tutorial we will some of useful collection classes e.g. ConcurrentHashMap, BlockingQueuewhich provides some of the very useful functionalities to build concurrent Java application. By the way this is not a comprehensive article explaining each feature of all these concurrent collections, Instead I will just try to list out why they are there, which Collection class they replace or provides alternative for. Idea is to keep it short and simple while highlighting key points of those useful java.util.concurrent collections.
Read more �

Senin, 28 Januari 2013

IdentityHashMap in Java was added in Java 1.4 but still it's one of those lesser known class in Java. The main difference between IdentityHashMap and HashMap in Java is that IdentityHashMap is a special implementation of Map interface which doesn't use equals() and hashCode() method for comparing object unlike other implementation of Map e.g. HashMap. Instead, IdentityHashMap uses equality operator "==" to compare keys and values in Java which makes it faster compare to HashMap and suitable where you need reference equality check and instead of logical equality. By the way, IdentityHashMap is a special implementation of Map interface much like EnumMap but it also violates general contract of Map interface which mandates using equals method for comparing Object. Also, IdentityHashMap vs HashMap is a good Java question and have been asked a couple of times.
Read more �

Jumat, 04 Januari 2013

NavigableMap in Java 6 is an extension of SortedMap like TreeMapwhich provides convenient navigation method like lowerKey, floorKey, ceilingKey and higherKey. NavigableMap is added on Java 1.6 and along with these popular navigation method it also provide ways to create a Sub Map from existing Map in Java e.g. headMap whose keys are less than specified key, tailMap whose keys are greater than specified key and a subMap which is strictly contains keys which falls between toKey and fromKey. All of these methods also provides a boolean to include specified key or not. TreeMapand ConcurrentSkipListMap are two concrete implementation of NavigableMap in Java 1.6 API. Though NavigableMap is not as popular as HashMap, ConcurrentHashMapor Hashtablebut given that TreeMap implements NavigableMap you already get all good things in a well known Map implementation.
Read more �

Minggu, 30 Desember 2012

java.util.Arrays class provides equals() and deepEquals() method to compare two Arrays in Java. Both of these are overloaded method to compare primitive arrays e.g. int, long, float, double and Object arrays e.g. Arrays.equals(Object[] , Object[]). Arrays.equals() returns true if both Arrays which it is comparing are null If both arrays pointing to same Array Object or they must be of the same length and contains the same element in each index. In all other cases, it returns false. Arrays.equals() calls equals() method of each Object while comparing Object arrays. One of the tricky question in Java related to Array comparison is Difference between Arrays.equals() and Arrays.deepEquals() method. Since both equals and deepEquals is used for array comparison, what is the difference between them becomes important. The short answer of this questions is that, Array's equals() method does not perform deep comparison and fails logical comparison in case of nested Array, on other hand deepEquals() perform deep comparison and returns logical comparison in case of nested array.
Read more �

Kamis, 27 Desember 2012

Printing array values in Java or values of array element in Java would have been much easier if arrays are allowed to directly prints its values whenever used inside System.out.println() or format and printf method, Similar to various classes in Java do this by overriding toString() method. Despite being an object, array in Java doesn't print any meaningful representation of its content when passed to System.out.println() or any other print methods. If you are using array in method argument or any other prominent place in code and actually interested in values of array then you don't have much choice than for loop until Java 1.4. Things has been changed since Java 5 because it introduced two extremely convenient methods for printing values of both primitive and object arrays in Java. Arrays.toString(array) and Arrays.deepToString(twoDimensionArray) can print values of any array. Main difference between Arrays.toString() and Arrays.deepToString is that deepToString is used to print values of multidimensional array which is far more convenient than nesting of multiple for loops. In this Java tutorial we will see 3 different ways of printing array values in Java or value of element from Array in Java.
Read more �

Minggu, 23 Desember 2012

You can remove duplicates or repeated elements from ArrayList in Java by converting ArrayList into HashSet in Java. but before doing that just keep in mind that Set doesn't preserver insertion order which is guaranteed by List, in fact that�s the main difference between List and Set in Java. So when you convert ArrayList to HashSet all duplicates elements will be removed but insertion order will be lost. Let�s see this in action by writing a Java program to remove duplicates from ArrayList in Java. In this Java collection tutorial we will see both approach of deleting duplicates from ArrayList e.g using Hashset and LinkedHashSet and compare order of elements in final ArrayList which contains no duplicates. If you are not very familiar of What is an ArrayList and HashSet in Java collection framework, I suggest reading Java ArrayList Example and 10 HashSet Example in Java. These articles contains good introduction of most common used collection in Java i.e. ArrayList and HashSet.
Read more �

Rabu, 19 Desember 2012

Sorting HashMap in Java is not as easy as it sounds because unfortunately Java API doesn't provide any utility method to sort HashMap based on keys and values. Sorting HashMap is not like sorting ArrayList or sorting Arrays in Java. If you are wondering why we can not use Collections.sort() method than for your information it only accepts List<E>, which leaves us to write our own utility methods to sort Map in Java. This is true for all types of Map like Hashtable, HashMap, and LinkedHashMap. TreeMap is an already a sorted Map so we don't need to sort it again. Why we need to sort HashMap in Java, Why can't we use TreeMap in place of HashMap is the question appears in most Java programmer's mind when they asked to sort HashMap in Java. Well, TreeMap is way slower than HashMap because it runs sorting operation with each insertion, update and removal and sometimes you don't really need an all time sorted Map, What you need is an ability to sort any Map implementation based upon its key and value. In the last couple of articles, we have seen How to loop or traverse Map in Java and in this Java tutorial we will see a couple of ways to sort HashMap in Java.
Read more �

Senin, 10 Desember 2012

Google Guava is an open source library which provides lots of useful utility to Java programmer, one of them is easy way to find intersection and union of two Set in Java. You might have used Google Guava for other functionality e.g. for overriding toString in easy way or Immutable Collection provided by Guava library. Along with Apache commons and Spring, Google Guava is a library you definitely want to include in your Project. Guava provides couple of static method to operate on Set in Java on package com.google.common.collect.Sets. There are two methods called intersection() and union() which provides intersection and union of two Sets in Java. In this example we have used HashSetas Set implementation but it will work with any Set implementation e.g. TreeSet or LinkedHashSet.
Read more �

Rabu, 05 Desember 2012

BlockingQueue in Java is added in Java 1.5 along with various other concurrent Utility classes like ConcurrentHashMap, Counting Semaphore, CopyOnWriteArrrayListetc. BlockingQueue is a unique collection type which not only store elements but also supports flow control by introducing blocking if either BlockingQueue is full or empty. take() method of BlockingQueue will block if Queue is empty and put() method of BlockingQueue will block if Queue is full. This property makes BlockingQueue an ideal choice for implementing Producer consumer design pattern where one thread insert element into BlockingQueue and other thread consumes it. In this Java tutorial we will learn about What is BlockingQueue in Java, How to use BlockingQueue, ArrayBlockingQueue and LinkedBlockingQueue and some important properties of it. 

Kamis, 08 November 2012

TreeSet, LinkedHashSet and HashSet all are implementation of Set interface and by virtue of that, they follows contract of Set interface i.e. they do not allow duplicate elements. Despite being from same type hierarchy, there are lot of difference between them; which is important to understand, so that you can choose most appropriate Set implementation based upon your requirement. By the way difference between TreeSet and HashSet or LinkedHashSet is also one of the popular Java Collection interview question, not as popular as Hashtable vs HashMap or ArrayList vs Vector but still appears in various Java interviews. In this article we will see difference between HashSet, TreeSet and LinkedHashSet on various points e.g. Ordering of elements, performance, allowing null etc and then we will see When to use TreeSet or LinkedHashSet or simply HashSet in Java.
Read more �

Minggu, 04 November 2012

Searching in Java Array sounds familiar? should be, because its one of frequently used operations in Java programming. Array is an index based data structure which is used to store elements but unlike Collection classes like ArrayList or HashSet which has contains() method, array in Java doesn't have any method to check whether an element is inside array or not. Java programming language provides several ways to search any element in Java array. In this Java tutorial we will see 4 examples of searching Array in Java for an element or object. Every example is different than other and some of them are faster and others are slow but take less memory. These technique also valid for different types of array e.g. primitive and object array. I always suggest to prefer List over Array until you need every bit of performance from your Java application, it not only convenient to work but also more extensible.
Read more �

Senin, 01 Oktober 2012

HashMap vs EnumMap in Java
What is the difference between EnumMap and HashMap in Java is the latest Java collection interview question which has been asked to a couple of my friends? This is one of the tricky Java questions, especially if you are not very much familiar with EnumMap in Java, which is not uncommon, given you can use it with only Enum keys. The main difference between EnumMap and HashMap is that EnumMap is a specialized Map implementation exclusively for Enum as key. Using Enum as key allows doing some implementation level optimization for high performance which is generally not possible with other objects as key. We have seen a lot of interview questions on HashMap in our article How HashMap works in Java but what we missed there is this question which is recently asked to some of my friends. Unlike HashMap, EnumMap is not applicable for every case but it's best suited when you have Enum as key. We have already covered basics of EnumMap and some EnumMap example in my last article What is EnumMap in Java and In this post, we will focus on key differences between HashMap and EnumMap in Java.
Read more �

Kamis, 23 Agustus 2012

How to convert Collection to String in Java
Many times we need to convert any Collection like Set or List into String like comma separated or any other delimiter delimited String. Though this is quite a trivial job for a Java programmer as you just need to Iterate through the loop and create a big String where individual String are separated by a delimiter, you still need to handle cases like the last element should not have delimiter or at a bare minimum you need to test that code. I like Joshua Bloch advice on Effective Java to use libraries for those common tasks let it be an internal proprietary library or any open source library as used in previous examples of Spring, Apache Commons or Google�s Guava but point is that you should avoid converting ArrayList to String like common task by yourself on application code.
Read more �