0% found this document useful (0 votes)
28 views

Java List

The document discusses Java lists. Some key points: - Lists in Java provide ordered collections that allow duplicate elements and null values. Common implementations are ArrayList and LinkedList. - The List interface inherits from Collection and provides methods to insert, retrieve, update, and delete elements by index. It can iterate forward and backward. - Common methods include add(), get(), set(), remove(), and clear(). The Collections class provides sort() to sort lists.

Uploaded by

Ashi Rana
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Java List

The document discusses Java lists. Some key points: - Lists in Java provide ordered collections that allow duplicate elements and null values. Common implementations are ArrayList and LinkedList. - The List interface inherits from Collection and provides methods to insert, retrieve, update, and delete elements by index. It can iterate forward and backward. - Common methods include add(), get(), set(), remove(), and clear(). The Collections class provides sort() to sort lists.

Uploaded by

Ashi Rana
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

UNIT -4

Java List
List in Java provides the facility to maintain the ordered collection. It contains the index-
based methods to insert, update, delete and search the elements. It can have the
duplicate elements also. We can also store the null elements in the list.

The List interface is found in the java.util package and inherits the Collection
interface.

It is a factory of ListIterator interface. Through the ListIterator, we can iterate the list
in forward and backward directions. The implementation classes of List interface
are ArrayList, LinkedList, Stack and Vector. The ArrayList and LinkedList are widely
used in Java programming.

The Vector class is deprecated since Java 5.

List Interface declaration

1. public interface List<E> extends Collection<E>

Java List Methods

Method Description

void add(int index, E element) It is used to insert the specified element


at the specified position in a list.

boolean add(E e) It is used to append the specified


element at the end of a list.

boolean addAll(Collection<? It is used to append all of the elements


extends E> c) in the specified collection to the end of a
list.

boolean addAll(int index, It is used to append all the elements in


Collection<? extends E> c) the specified collection, starting at the
specified position of the list.

void clear() It is used to remove all of the elements


from this list.
boolean equals(Object o) It is used to compare the specified
object with the elements of a list.

int hashcode() It is used to return the hash code value


for a list.

E get(int index) It is used to fetch the element from the


particular position of the list.

boolean isEmpty() It returns true if the list is empty,


otherwise false.

int lastIndexOf(Object o) It is used to return the index in this list of


the last occurrence of the specified
element, or -1 if the list does not contain
this element.

Object[] toArray() It is used to return an array containing


all of the elements in this list in the
correct order.

<T> T[] toArray(T[] a) It is used to return an array containing


all of the elements in this list in the
correct order.

boolean contains(Object o) It returns true if the list contains the


specified element

boolean containsAll(Collection<?> It returns true if the list contains all the


c) specified element

int indexOf(Object o) It is used to return the index in this list of


the first occurrence of the specified
element, or -1 if the List does not
contain this element.

E remove(int index) It is used to remove the element present


at the specified position in the list.

boolean remove(Object o) It is used to remove the first occurrence


of the specified element.

boolean removeAll(Collection<?> It is used to remove all the elements


c) from the list.

void replaceAll(UnaryOperator<E> It is used to replace all the elements


operator) from the list with the specified element.
void retainAll(Collection<?> c) It is used to retain all the elements in the
list that are present in the specified
collection.

E set(int index, E element) It is used to replace the specified


element in the list, present at the
specified position.

void sort(Comparator<? super E> It is used to sort the elements of the list
c) on the basis of specified comparator.

Spliterator<E> spliterator() It is used to create spliterator over the


elements in a list.

List<E> subList(int fromIndex, int It is used to fetch all the elements lies
toIndex) within the given range.

int size() It is used to return the number of


elements present in the list.

Java List vs ArrayList


List is an interface whereas ArrayList is the implementation class of List.

How to create List


The ArrayList and LinkedList classes provide the implementation of List interface. Let's
see the examples to create the List:

23M
481
HTML Tutorial

1. //Creating a List of type String using ArrayList


2. List<String> list=new ArrayList<String>();
3.
4. //Creating a List of type Integer using ArrayList
5. List<Integer> list=new ArrayList<Integer>();
6.
7. //Creating a List of type Book using ArrayList
8. List<Book> list=new ArrayList<Book>();
9.
10. //Creating a List of type String using LinkedList
11. List<String> list=new LinkedList<String>();

In short, you can create the List of any type. The ArrayList<T> and LinkedList<T>
classes are used to specify the type. Here, T denotes the type.

Java List Example


Let's see a simple example of List where we are using the ArrayList class as the
implementation.

1. import java.util.*;
2. public class ListExample1{
3. public static void main(String args[]){
4. //Creating a List
5. List<String> list=new ArrayList<String>();
6. //Adding elements in the List
7. list.add("Mango");
8. list.add("Apple");
9. list.add("Banana");
10. list.add("Grapes");
11. //Iterating the List element using for-each loop
12. for(String fruit:list)
13. System.out.println(fruit);
14.
15. }
16. }
Test it Now
Output:

Mango
Apple
Banana
Grapes

How to convert Array to List


We can convert the Array to List by traversing the array and adding the element in
list one by one using list.add() method. Let's see a simple example to convert array
elements into List.

1. import java.util.*;
2. public class ArrayToListExample{
3. public static void main(String args[]){
4. //Creating Array
5. String[] array={"Java","Python","PHP","C++"};
6. System.out.println("Printing Array: "+Arrays.toString(array));
7. //Converting Array to List
8. List<String> list=new ArrayList<String>();
9. for(String lang:array){
10. list.add(lang);
11. }
12. System.out.println("Printing List: "+list);
13.
14. }
15. }
Test it Now

Output:

Printing Array: [Java, Python, PHP, C++]


Printing List: [Java, Python, PHP, C++]
How to convert List to Array
We can convert the List to Array by calling the list.toArray() method. Let's see a simple
example to convert list elements into array.

1. import java.util.*;
2. public class ListToArrayExample{
3. public static void main(String args[]){
4. List<String> fruitList = new ArrayList<>();
5. fruitList.add("Mango");
6. fruitList.add("Banana");
7. fruitList.add("Apple");
8. fruitList.add("Strawberry");
9. //Converting ArrayList to Array
10. String[] array = fruitList.toArray(new String[fruitList.size()]);
11. System.out.println("Printing Array: "+Arrays.toString(array));
12. System.out.println("Printing List: "+fruitList);
13. }
14. }
Test it Now

Output:

Printing Array: [Mango, Banana, Apple, Strawberry]


Printing List: [Mango, Banana, Apple, Strawberry]

Get and Set Element in List


The get() method returns the element at the given index,

whereas the set() method changes or replaces the element.


1. import java.util.*;
2. public class ListExample2{
3. public static void main(String args[]){
4. //Creating a List
5. List<String> list=new ArrayList<String>();
6. //Adding elements in the List
7. list.add("Mango");
8. list.add("Apple");
9. list.add("Banana");
10. list.add("Grapes");
11. //accessing the element
12.

System.out.println("Returning element: "+list.get(1));//it will return the 2nd element, bec


ause index starts from 0
13. //changing the element
14. list.set(1,"Dates");
15. //Iterating the List element using for-each loop
16. for(String fruit:list)
17. System.out.println(fruit);
18.
19. }
20. }
Test it Now

Output:

Returning element: Apple


Mango
Dates
Banana
Grapes

How to Sort List


There are various ways to sort the List, here we are going to use Collections.sort()
method to sort the list element. The java.util package provides a utility
class Collections which has the static method sort(). Using
the Collections.sort() method, we can easily sort any List.

1. import java.util.*;
2. class SortArrayList{
3. public static void main(String args[]){
4. //Creating a list of fruits
5. List<String> list1=new ArrayList<String>();
6. list1.add("Mango");
7. list1.add("Apple");
8. list1.add("Banana");
9. list1.add("Grapes");
10. //Sorting the list
11. Collections.sort(list1);
12. //Traversing list through the for-each loop
13. for(String fruit:list1)
14. System.out.println(fruit);
15.
16. System.out.println("Sorting numbers...");
17. //Creating a list of numbers
18. List<Integer> list2=new ArrayList<Integer>();
19. list2.add(21);
20. list2.add(11);
21. list2.add(51);
22. list2.add(1);
23. //Sorting the list
24. Collections.sort(list2);
25. //Traversing list through the for-each loop
26. for(Integer number:list2)
27. System.out.println(number);
28. }
29.
30. }

Output:

Apple
Banana
Grapes
Mango
Sorting numbers...
1
11
21
51

Java ListIterator Interface


ListIterator Interface is used to traverse the element in a backward and forward
direction.

ListIterator Interface declaration

1. public interface ListIterator<E> extends Iterator<E>

Methods of Java ListIterator Interface:

Method Description

void add(E e) This method inserts the specified element into the list.

boolean This method returns true if the list iterator has more
hasNext() elements while traversing the list in the forward direction.

E next() This method returns the next element in the list and
advances the cursor position.

int nextIndex() This method returns the index of the element that would be
returned by a subsequent call to next()
boolean This method returns true if this list iterator has more
hasPrevious() elements while traversing the list in the reverse direction.

E previous() This method returns the previous element in the list and
moves the cursor position backward.

E previousIndex() This method returns the index of the element that would be
returned by a subsequent call to previous().

void remove() This method removes the last element from the list that
was returned by next() or previous() methods

void set(E e) This method replaces the last element returned by next()
or previous() methods with the specified element.

Example of ListIterator Interface

1. import java.util.*;
2. public class ListIteratorExample1{
3. public static void main(String args[]){
4. List<String> al=new ArrayList<String>();
5. al.add("Amit");
6. al.add("Vijay");
7. al.add("Kumar");
8. al.add(1,"Sachin");
9. ListIterator<String> itr=al.listIterator();
10. System.out.println("Traversing elements in forward direction");
11. while(itr.hasNext()){
12.
13. System.out.println("index:"+itr.nextIndex()+" value:"+itr.next());
14. }
15. System.out.println("Traversing elements in backward direction");
16. while(itr.hasPrevious()){
17.
18. System.out.println("index:"+itr.previousIndex()+" value:"+itr.previous());
19. }
20. }
21. }

Output:

Traversing elements in forward direction


index:0 value:Amit
index:1 value:Sachin
index:2 value:Vijay
index:3 value:Kumar
Traversing elements in backward direction
index:3 value:Kumar
index:2 value:Vijay
index:1 value:Sachin
index:0 value:Amit

Example of List: Book


Let's see an example of List where we are adding the Books.

1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class ListExample5 {
15. public static void main(String[] args) {
16. //Creating list of Books
17. List<Book> list=new ArrayList<Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20.

Book b2=new Book(102,"Data Communications and Networking","Forouzan","Mc Gr


aw Hill",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to list
23. list.add(b1);
24. list.add(b2);
25. list.add(b3);
26. //Traversing list
27. for(Book b:list){
28. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
29. }
30. }
31. }
Test it Now

Output:

101 Let us C Yashwant Kanetkar BPB 8


102 Data Communications and Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6

Java TreeSet class


Java TreeSet class implements the Set interface that uses a tree for storage. It inherits
AbstractSet class and implements the NavigableSet interface. The objects of the
TreeSet class are stored in ascending order.

The important points about Java TreeSet class are:

o Java TreeSet class contains unique elements only like HashSet.


o Java TreeSet class access and retrieval times are quiet fast.
o Java TreeSet class doesn't allow null element.
o Java TreeSet class is non synchronized.
o Java TreeSet class maintains ascending order.

Hierarchy of TreeSet class


As shown in the above diagram, Java TreeSet class implements the NavigableSet
interface. The NavigableSet interface extends SortedSet, Set, Collection and Iterable
interfaces in hierarchical order.

TreeSet class declaration


Let's see the declaration for java.util.TreeSet class.

Constructors of Java TreeSet class

Constructor Description

TreeSet() It is used to construct an empty tree set that will be


sorted in ascending order according to the natural
order of the tree set.

TreeSet(Collection<? extends It is used to build a new tree set that contains the
E> c) elements of the collection c.

TreeSet(Comparator<? super It is used to construct an empty tree set that will be


E> comparator) sorted according to given comparator.

TreeSet(SortedSet<E> s) It is used to build a TreeSet that contains the


elements of the given SortedSet.

Methods of Java TreeSet class

Method Description
boolean add(E e) It is used to add the specified element
to this set if it is not already present.

boolean addAll(Collection<? extends E> c) It is used to add all of the elements in


the specified collection to this set.

E ceiling(E e) It returns the equal or closest greatest


element of the specified element from
the set, or null there is no such
element.

Comparator<? super E> comparator() It returns comparator that arranged


elements in order.

Iterator descendingIterator() It is used iterate the elements in


descending order.

NavigableSet descendingSet() It returns the elements in reverse


order.

E floor(E e) It returns the equal or closest least


element of the specified element from
the set, or null there is no such
element.

SortedSet headSet(E toElement) It returns the group of elements that


are less than the specified element.

NavigableSet headSet(E toElement, boolean It returns the group of elements that


inclusive) are less than or equal to(if, inclusive is
true) the specified element.

E higher(E e) It returns the closest greatest element


of the specified element from the set,
or null there is no such element.

Iterator iterator() It is used to iterate the elements in


ascending order.
E lower(E e) It returns the closest least element of
the specified element from the set, or
null there is no such element.

E pollFirst() It is used to retrieve and remove the


lowest(first) element.

E pollLast() It is used to retrieve and remove the


highest(last) element.

Spliterator spliterator() It is used to create a late-binding and


fail-fast spliterator over the elements.

NavigableSet subSet(E fromElement, It returns a set of elements that lie


boolean fromInclusive, E toElement, boolean between the given range.
toInclusive)

SortedSet subSet(E fromElement, E It returns a set of elements that lie


toElement)) between the given range which
includes fromElement and excludes
toElement.

SortedSet tailSet(E fromElement) It returns a set of elements that are


greater than or equal to the specified
element.

NavigableSet tailSet(E fromElement, boolean It returns a set of elements that are


inclusive) greater than or equal to (if, inclusive is
true) the specified element.

boolean contains(Object o) It returns true if this set contains the


specified element.

boolean isEmpty() It returns true if this set contains no


elements.

boolean remove(Object o) It is used to remove the specified


element from this set if it is present.

void clear() It is used to remove all of the elements


from this set.

Object clone() It returns a shallow copy of this


TreeSet instance.

E first() It returns the first (lowest) element


currently in this sorted set.

E last() It returns the last (highest) element


currently in this sorted set.

int size() It returns the number of elements in


this set.

Java TreeSet Examples

Java TreeSet Example 1:


Let's see a simple example of Java TreeSet.

1. import java.util.*;
2. class TreeSet1{
3. public static void main(String args[]){
4. //Creating and adding elements
5. TreeSet<String> al=new TreeSet<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10. //Traversing elements
11. Iterator<String> itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Test it Now

Output:

Ajay
Ravi
Vijay

Java TreeSet Example 2:


Let's see an example of traversing elements in descending order.

1. import java.util.*;
2. class TreeSet2{
3. public static void main(String args[]){
4. TreeSet<String> set=new TreeSet<String>();
5. set.add("Ravi");
6. set.add("Vijay");
7. set.add("Ajay");
8. System.out.println("Traversing element through Iterator in descending order");
9. Iterator i=set.descendingIterator();
10. while(i.hasNext())
11. {
12. System.out.println(i.next());
13. }
14.
15. }
16. }
Test it Now

Output:

Traversing element through Iterator in descending order


Vijay
Ravi
Ajay
Traversing element through NavigableSet in descending order
Vijay
Ravi
Ajay

Java TreeSet Example 3:


Let's see an example to retrieve and remove the highest and lowest Value.

1. import java.util.*;
2. class TreeSet3{
3. public static void main(String args[]){
4. TreeSet<Integer> set=new TreeSet<Integer>();
5. set.add(24);
6. set.add(66);
7. set.add(12);
8. set.add(15);
9. System.out.println("Highest Value: "+set.pollFirst());
10. System.out.println("Lowest Value: "+set.pollLast());
11. }
12. }

Output:

Highest Value: 12
Lowest Value: 66

Java TreeSet Example 4:


In this example, we perform various NavigableSet operations.

1. import java.util.*;
2. class TreeSet4{
3. public static void main(String args[]){
4. TreeSet<String> set=new TreeSet<String>();
5. set.add("A");
6. set.add("B");
7. set.add("C");
8. set.add("D");
9. set.add("E");
10. System.out.println("Initial Set: "+set);
11.
12. System.out.println("Reverse Set: "+set.descendingSet());
13.
14. System.out.println("Head Set: "+set.headSet("C", true));
15.
16. System.out.println("SubSet: "+set.subSet("A", false, "E", true));
17.
18. System.out.println("TailSet: "+set.tailSet("C", false));
19. }
20. }

Output:

Initial Set: [A, B, C, D, E]


Reverse Set: [E, D, C, B, A]
Head Set: [A, B, C]
SubSet: [B, C, D, E]
TailSet: [D, E]

Java TreeSet Example 4:


In this example, we perform various SortedSetSet operations.

1. import java.util.*;
2. class TreeSet4{
3. public static void main(String args[]){
4. TreeSet<String> set=new TreeSet<String>();
5. set.add("A");
6. set.add("B");
7. set.add("C");
8. set.add("D");
9. set.add("E");
10.
11. System.out.println("Intial Set: "+set);
12.
13. System.out.println("Head Set: "+set.headSet("C"));
14.
15. System.out.println("SubSet: "+set.subSet("A", "E"));
16.
17. System.out.println("TailSet: "+set.tailSet("C"));
18. }
19. }

Output:

Intial Set: [A, B, C, D, E]


Head Set: [A, B]
SubSet: [A, B, C, D]
TailSet: [C, D, E]

Java TreeSet Example: Book


Let's see a TreeSet example where we are adding books to set and printing all the
books. The elements in TreeSet must be of a Comparable type. String and Wrapper
classes are Comparable by default. To add user-defined objects in TreeSet, you need
to implement the Comparable interface.

1. import java.util.*;
2. class Book implements Comparable<Book>{
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. public int compareTo(Book b) {
14. if(id>b.id){
15. return 1;
16. }else if(id<b.id){
17. return -1;
18. }else{
19. return 0;
20. }
21. }
22. }
23. public class TreeSetExample {
24. public static void main(String[] args) {
25. Set<Book> set=new TreeSet<Book>();
26. //Creating Books
27. Book b1=new Book(121,"Let us C","Yashwant Kanetkar","BPB",8);
28. Book b2=new Book(233,"Operating System","Galvin","Wiley",6);
29.
Book b3=new Book(101,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);

30. //Adding Books to TreeSet


31. set.add(b1);
32. set.add(b2);
33. set.add(b3);
34. //Traversing TreeSet
35. for(Book b:set){
36. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
37. }
38. }
39. }

Output:

101 Data Communications & Networking Forouzan Mc Graw Hill 4


121 Let us C Yashwant Kanetkar BPB 8
233 Operating System Galvin Wiley 6

Java Map Interface


A map contains values on the basis of key, i.e. key and value pair. Each key and value
pair is known as an entry. A Map contains unique keys.

A Map is useful if you have to search, update or delete elements on the basis of a key.

Java Map Hierarchy


There are two interfaces for implementing Map in java: Map and SortedMap, and three
classes: HashMap, LinkedHashMap, and TreeMap. The hierarchy of Java Map is given
below:
A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and
LinkedHashMap allow null keys and values, but TreeMap doesn't allow any null key or
value.

13.4M

216

Triggers in SQL (Hindi)

A Map can't be traversed, so you need to convert it into Set


using keySet() or entrySet() method.
Class Description

HashMap HashMap is the implementation of Map, but it doesn't maintain any


order.

LinkedHashMa LinkedHashMap is the implementation of Map. It inherits HashMap


p class. It maintains insertion order.

TreeMap TreeMap is the implementation of Map and SortedMap. It maintains


ascending order.

Useful methods of Map interface

Method Description

V put(Object key, Object value) It is used to insert an entry in the map.

void putAll(Map map) It is used to insert the specified map in the


map.

V putIfAbsent(K key, V value) It inserts the specified value with the specified
key in the map only if it is not already specified.

V remove(Object key) It is used to delete an entry for the specified


key.

boolean remove(Object key, Object It removes the specified values with the
value) associated specified keys from the map.

Set keySet() It returns the Set view containing all the keys.

Set<Map.Entry<K,V>> entrySet() It returns the Set view containing all the keys
and values.

void clear() It is used to reset the map.

V compute(K key, BiFunction<? It is used to compute a mapping for the


super K,? super V,? extends V> specified key and its current mapped value (or
remappingFunction) null if there is no current mapping).

V computeIfAbsent(K key, It is used to compute its value using the given


Function<? super K,? extends V> mapping function, if the specified key is not
mappingFunction) already associated with a value (or is mapped
to null), and enters it into this map unless null.

V computeIfPresent(K key, It is used to compute a new mapping given the


BiFunction<? super K,? super V,? key and its current mapped value if the value
extends V> remappingFunction) for the specified key is present and non-null.

boolean containsValue(Object value) This method returns true if some value equal to
the value exists within the map, else return
false.

boolean containsKey(Object key) This method returns true if some key equal to
the key exists within the map, else return false.

boolean equals(Object o) It is used to compare the specified Object with


the Map.

void forEach(BiConsumer<? super It performs the given action for each entry in
K,? super V> action) the map until all entries have been processed
or the action throws an exception.

V get(Object key) This method returns the object that contains


the value associated with the key.

V getOrDefault(Object key, V It returns the value to which the specified key is


defaultValue) mapped, or defaultValue if the map contains no
mapping for the key.
int hashCode() It returns the hash code value for the Map

boolean isEmpty() This method returns true if the map is empty;


returns false if it contains at least one key.

V merge(K key, V value, If the specified key is not already associated


BiFunction<? super V,? super V,? with a value or is associated with null,
extends V> remappingFunction) associates it with the given non-null value.

V replace(K key, V value) It replaces the specified value for a specified


key.

boolean replace(K key, V oldValue, It replaces the old value with the new value for
V newValue) a specified key.

void replaceAll(BiFunction<? super It replaces each entry's value with the result of
K,? super V,? extends V> function) invoking the given function on that entry until all
entries have been processed or the function
throws an exception.

Collection values() It returns a collection view of the values


contained in the map.

int size() This method returns the number of entries in


the map.

Map.Entry Interface
Entry is the subinterface of Map. So we will be accessed it by Map.Entry name. It
returns a collection-view of the map, whose elements are of this class. It provides
methods to get key and value.

Methods of Map.Entry interface

Method Description
K getKey() It is used to obtain a key.

V getValue() It is used to obtain value.

int hashCode() It is used to obtain hashCode.

V setValue(V value) It is used to replace the value


corresponding to this entry with
the specified value.

boolean equals(Object o) It is used to compare the


specified object with the other
existing objects.

static <K extends Comparable<? super K>,V> It returns a comparator that


Comparator<Map.Entry<K,V>> comparingByKey() compare the objects in natural
order on key.

static <K,V> Comparator<Map.Entry<K,V>> It returns a comparator that


comparingByKey(Comparator<? super K> cmp) compare the objects by key using
the given Comparator.

static <K,V extends Comparable<? super V>> It returns a comparator that


Comparator<Map.Entry<K,V>> compare the objects in natural
comparingByValue() order on value.

static <K,V> Comparator<Map.Entry<K,V>> It returns a comparator that


comparingByValue(Comparator<? super V> cmp) compare the objects by value
using the given Comparator.

Java Map Example: Non-Generic (Old Style)


1. //Non-generic
2. import java.util.*;
3. public class MapExample1 {
4. public static void main(String[] args) {
5. Map map=new HashMap();
6. //Adding elements to map
7. map.put(1,"Amit");
8. map.put(5,"Rahul");
9. map.put(2,"Jai");
10. map.put(6,"Amit");
11. //Traversing Map
12. Set set=map.entrySet();//Converting to Set so that we can traverse
13. Iterator itr=set.iterator();
14. while(itr.hasNext()){
15. //Converting to Map.Entry so that we can get key and value separately
16. Map.Entry entry=(Map.Entry)itr.next();
17. System.out.println(entry.getKey()+" "+entry.getValue());
18. }
19. }
20. }

Output:

1 Amit
2 Jai
5 Rahul
6 Amit

Java Map Example: Generic (New Style)

1. import java.util.*;
2. class MapExample2{
3. public static void main(String args[]){
4. Map<Integer,String> map=new HashMap<Integer,String>();
5. map.put(100,"Amit");
6. map.put(101,"Vijay");
7. map.put(102,"Rahul");
8. //Elements can traverse in any order
9. for(Map.Entry m:map.entrySet()){
10. System.out.println(m.getKey()+" "+m.getValue());
11. }
12. }
13. }

Output:

102 Rahul
100 Amit
101 Vijay

Java Map Example: comparingByKey()

1. import java.util.*;
2. class MapExample3{
3. public static void main(String args[]){
4. Map<Integer,String> map=new HashMap<Integer,String>();
5. map.put(100,"Amit");
6. map.put(101,"Vijay");
7. map.put(102,"Rahul");
8. //Returns a Set view of the mappings contained in this map
9. map.entrySet()
10. //Returns a sequential Stream with this collection as its source
11. .stream()
12. //Sorted according to the provided Comparator
13. .sorted(Map.Entry.comparingByKey())
14. //Performs an action for each element of this stream
15. .forEach(System.out::println);
16. }
17. }

Output:

100=Amit
101=Vijay
102=Rahul

Java Map Example: comparingByKey() in Descending Order

1. import java.util.*;
2. class MapExample4{
3. public static void main(String args[]){
4. Map<Integer,String> map=new HashMap<Integer,String>();
5. map.put(100,"Amit");
6. map.put(101,"Vijay");
7. map.put(102,"Rahul");
8. //Returns a Set view of the mappings contained in this map
9. map.entrySet()
10. //Returns a sequential Stream with this collection as its source
11. .stream()
12. //Sorted according to the provided Comparator
13. .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
14. //Performs an action for each element of this stream
15. .forEach(System.out::println);
16. }
17. }

Output:

102=Rahul
101=Vijay
100=Amit

Java Map Example: comparingByValue()

1. import java.util.*;
2. class MapExample5{
3. public static void main(String args[]){
4. Map<Integer,String> map=new HashMap<Integer,String>();
5. map.put(100,"Amit");
6. map.put(101,"Vijay");
7. map.put(102,"Rahul");
8. //Returns a Set view of the mappings contained in this map
9. map.entrySet()
10. //Returns a sequential Stream with this collection as its source
11. .stream()
12. //Sorted according to the provided Comparator
13. .sorted(Map.Entry.comparingByValue())
14. //Performs an action for each element of this stream
15. .forEach(System.out::println);
16. }
17. }

Output:

100=Amit
102=Rahul
101=Vijay
Java Map Example: comparingByValue() in Descending Order

1. import java.util.*;
2. class MapExample6{
3. public static void main(String args[]){
4. Map<Integer,String> map=new HashMap<Integer,String>();
5. map.put(100,"Amit");
6. map.put(101,"Vijay");
7. map.put(102,"Rahul");
8. //Returns a Set view of the mappings contained in this map
9. map.entrySet()
10. //Returns a sequential Stream with this collection as its source
11. .stream()
12. //Sorted according to the provided Comparator
13. .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
14. //Performs an action for each element of this stream
15. .forEach(System.out::println);
16. }
17. }

Output:

101=Vijay
102=Rahul
100=Amit

You might also like