Java Reference
In-Depth Information
System.out.println(cMap.putIfAbsent("one", "nine"));
System.out.println(cMap.putIfAbsent("two", "two"));
System.out.println(cMap.remove("one", "two"));
System.out.println(cMap.replace("one", "two"));
System.out.println("Concurrent Map: " + cMap);
}
}
Concurrent Map: {one=one}
one
null
false
one
Concurrent Map: {one=two, two=two}
Concurrent and Navigable Maps
A concurrent navigable map is the concurrent and navigable version of the map. An instance of the
ConcurrentNavigableMap
interface represents a concurrent and navigable map. The interface inherits from the
ConcurrentMap
and
NavigableMap
interfaces.
The
ConcurrentSkipListMap
is the implementation class for the
ConcurrentNavigableMap
interface.
I have discussed both the concurrent map and navigable map. Please refer to the examples of both kinds for
using the
ConcurrentNavigableMap
.
Applying Algorithms to Collections
The Collections Framework lets you apply many types of algorithms on all or a few elements of a collection. It lets you
search through a collection for a value; sort and shuffle elements of a collection; get a read-only view of a collection;
etc. The good news is that all of these features are provided in one class named
Collections
. Notice that we have a
similarly named interfaced called
Collection
, which is the ancestor of most of the collection interfaces defined in the
Collections Framework. The
Collections
class consists of all static methods. If you want to apply any algorithm to a
collection, you need to look at the list of methods in this class before you writing your own code.
Sorting a List
You can use one of the following two static methods in the
Collections
class to sort the elements of a
List
:
<T extends Comparable<? super T>> void sort(List<T> list)
: It sorts the elements in
a
List
in the
natural order
defined by the
Comparable
interface that is implemented by the
elements in the
List
. Each element in the
List
must implement the
Comparable
interface and
they must be comparable to each other.
•
<T> void sort(List<T> list, Comparator<? super T> c)
: It lets you pass a
Comparator
object to define a custom ordering of the elements.
•