Java List
Java List
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.
Method Description
void sort(Comparator<? super E> It is used to sort the elements of the list
c) on the basis of specified comparator.
List<E> subList(int fromIndex, int It is used to fetch all the elements lies
toIndex) within the given range.
23M
481
HTML Tutorial
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.
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
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:
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:
Output:
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
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.
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:
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.
Output:
Constructor Description
TreeSet(Collection<? extends It is used to build a new tree set that contains the
E> c) elements of the collection c.
Method Description
boolean add(E e) It is used to add the specified element
to this set if it is not already present.
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
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:
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
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:
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:
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);
Output:
A Map is useful if you have to search, update or delete elements on the basis of a key.
13.4M
216
Method Description
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.
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.
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.
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.
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.
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.
Method Description
K getKey() It is used to obtain a key.
Output:
1 Amit
2 Jai
5 Rahul
6 Amit
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
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
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
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