1. Overview
interface Job { void post(); } Job job1 = new Job() { @Override public void post() { System.out.println("Posting job 1 now"); }
Java Tutorials for Freshers and Experience developers, Programming interview Questions, Data Structure and Algorithms interview Programs, Kotlin programs, String Programs, Java 8 Stream API, Spring Boot and Troubleshooting common issues.
interface Job { void post(); } Job job1 = new Job() { @Override public void post() { System.out.println("Posting job 1 now"); }
HashMap helps one object as an index to another object as the value. List index will be always a number whereas in Map it can be String, Integer, Float or Student or Trade objects.
package com.javaprogramto.arrays.toiterabale; /** * * Array Iterate example using loops * * @author javaprogramto.com * */ public class ArrayIterate { public static void main(String[] args) { // string array String[] names = new String[] {"john", "Amal", "Paul"}; // iterating array over its values. for(int index=0; index< names.length ; index++) { System.out.println(names[index]); } } }
john Amal Paul
package com.javaprogramto.arrays.toiterabale; import java.util.Arrays; import java.util.Iterator; import java.util.List; /** * * Example to convert Java Array to Iterable before Java 8 * * @author javaprogramto.com * */ public class JavaArrayToIterableExample { public static void main(String[] args) { // string array String[] names = new String[] {"john", "Amal", "Paul"}; // string array to list conversion List<String> namesList = Arrays.asList(names); // List to iterable Iterator<String> it = namesList.iterator(); // printing each value from iterator. while(it.hasNext()) { System.out.println(it.next()); } } }
john Amal Paul
import java.util.Arrays; import java.util.Iterator; import java.util.stream.Stream; /** * * Example to convert Java Array to Iterable using Java 8 Arrays.stream() * * @author javaprogramto.com * */ public class JavaArrayToIterableExampleJava8 { public static void main(String[] args) { // string array String[] names = new String[] {"john", "Amal", "Paul"}; System.out.println("Multi line solution"); // Convert string array to Stream<String> Stream<String> namesList = Arrays.stream(names); // Stream to iterable Iterator<String> it = namesList.iterator(); // printing each value from iterator. while(it.hasNext()) { System.out.println(it.next()); } // singel line System.out.println("\nIn single line"); Arrays.stream(names).iterator().forEachRemaining(name -> System.out.println(name)); } }
Multi line solution john Amal Paul In single line john Amal Paul
public class JavaStringToIterableExampleJava9 { public static void main(String[] args) { // string String numbers = "1 2 3 4 5 6"; // string to string array String[] numbersArray = numbers.split(" "); System.out.println("Multi line solution"); // Convert string array to Stream<String> Stream<String> numbersList = Arrays.stream(numbersArray); // Stream to iterable Iterator<String> it = numbersList.iterator(); // printing each value from iterator. while(it.hasNext()) { System.out.println(it.next()); } // singel line System.out.println("\nIn single line"); Arrays.stream(numbersArray).iterator().forEachRemaining(name -> System.out.println(name)); } }
Multi line solution 1 2 3 4 5 6 In single line 1 2 3 4 5 6
In this article, We will learn how to sort ArrayList in descending order in java. Sometimes this is referred as collections reverse or decreasing order.
To get the list in the reverse order, we need to use Collections.reverseOrder() and Collections.sort() methods together.
We have already shown how to sort list in ascending order using Collections.sort() method.
In the below examples, we are using the built-in comparator from the reverseOrder() method and passing it to the Collections.sort() method.
package com.javaprogramto.java8.arraylist; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class ArrayListReverseOrder1 { public static void main(String[] args) { // Creating ArrayList List<Integer> numbersList = new ArrayList<>(); // Adding values to List numbersList.add(150); numbersList.add(50); numbersList.add(250); numbersList.add(500); numbersList.add(350); // printing before sorting System.out.println("Before sorting : " + numbersList); // Getting the descending order comparator Comparator<Integer> reverseComparator = Collections.reverseOrder(); // Sorting with the reverse comparator with sort() method. // sort() method internally uses this comparator to sort in the descending order Collections.sort(numbersList, reverseComparator); // printing the final list after reverse order sorting. Original list only // sorted. System.out.println("After sorting : " + numbersList); } }
Output:
Before sorting : [150, 50, 250, 500, 350] After sorting : [500, 350, 250, 150, 50]
Next, look at the another way to sort the arraylist in descending order using two methods as below.
Collections.sort(arraylist); --> first sorts the list in the ascending order
Collections.reverse(arraylist); --> Next, reverse the sorted list.
Example:
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ArrayListReverseOrder2 { public static void main(String[] args) { // Creating ArrayList List<Integer> numbersList = new ArrayList<>(); // Adding values to List numbersList.add(150); numbersList.add(50); numbersList.add(250); numbersList.add(500); numbersList.add(350); // printing before sorting System.out.println("Before sorting : " + numbersList); // sorting the list in the ascending order Collections.sort(numbersList); // reversing the sorted list into descending order Collections.reverse(numbersList); // printing the final list after reverse order sorting. Original list only // sorted. System.out.println("After sorting : " + numbersList); } }
This program also produces the same output as in the section 2.
Sorting list in reverse order is pretty easy from stream.sorted(Collections.reverseOrder()) in java 8 api.
We can use parallelStream() method to work efficiently with larger data volumes.
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; public class ArrayListReverseOrder2 { public static void main(String[] args) { // Creating ArrayList List<Integer> numbersList = new ArrayList<>(); // Adding values to List numbersList.add(150); numbersList.add(50); numbersList.add(250); numbersList.add(500); numbersList.add(350); // printing before sorting System.out.println("Before sorting : " + numbersList); List<Integer> descendingList = numbersList.stream() .sorted(Collections.reverseOrder()) .collect(Collectors.toList()); // printing the final list after reverse order sorting. Original list only // sorted. System.out.println("After sorting : " + descendingList); } }
In this article, We have seen how to sort the ArrayList in descending order in older and new java 8 streams.
package com.javaprogramto.collections.hashmap; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Collectors; public class SortHashMapByValues { public static void main(String[] args) { // creating HashMap Map<String, Integer> namesAges = new HashMap<>(); // storing the values namesAges.put("Hari", 35); namesAges.put("Jhon", 30); namesAges.put("Jakey", 50); namesAges.put("kane", 45); Map<String, Integer> sortByValueMap = namesAges.entrySet().stream().sorted(Entry.comparingByValue()) .collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue(), (entry1, entry2) -> entry2, LinkedHashMap::new)); System.out.println("HashMap before sorting by value - " + namesAges); System.out.println("HashMap after sorting by value - " + sortByValueMap); } }
HashMap before sorting by value - {Hari=35, Jakey=50, Jhon=30, kane=45} HashMap after sorting by value - {Jhon=30, Hari=35, kane=45, Jakey=50}
package com.javaprogramto.collections.hashmap; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.stream.Collector; import java.util.stream.Collectors; import java.util.stream.Stream; public class SortHashMapByValues { public static void main(String[] args) { // creating HashMap Map<String, Integer> namesAges = new HashMap<>(); // storing the values namesAges.put("Hari", 35); namesAges.put("Jhon", 30); namesAges.put("Jakey", 50); namesAges.put("kane", 45); // Step 1: Getting the entry set from map Set<Map.Entry<String, Integer>> entrySet = namesAges.entrySet(); // Step 2: converting entry set to stream Stream<Entry<String, Integer>> stream = entrySet.stream(); // Step 3: comparator to sort using values. Comparator<Map.Entry<String, Integer>> comparator = Entry.comparingByValue(); // Step 4: sorting the stream using comparator created in above step. Stream<Entry<String, Integer>> sortedStream = stream.sorted(comparator); // Step 5: Getting the each key and value from entry object from above stream. // Finally, adding each entry to the LinkedHashMap. // LinkedHashMap is used to preserve the insertion order. If you do not collect // object into LinkedHashMap then final sorted map looks like same as the // original map before sorting. Collector<Entry<String, Integer>, ?, Map<String, Integer>> toMap = Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue(), (entry1, entry2) -> entry2, LinkedHashMap::new); // Step 6: Collecting the sorted stream into Map. Map<String, Integer> finalSortedByValueMap = sortedStream.collect(toMap); // printing System.out.println("HashMap before sorting by value - " + namesAges); System.out.println("HashMap after sorting by value - " + finalSortedByValueMap); } }
package com.javaprogramto.collections.hashmap; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.stream.Collector; import java.util.stream.Collectors; import java.util.stream.Stream; public class SortHashMapByValues { public static void main(String[] args) { // creating HashMap Map<String, Integer> namesAges = new HashMap<>(); // storing the values namesAges.put("Hari", 35); namesAges.put("Jhon", 30); namesAges.put("Jakey", 50); namesAges.put("kane", 45); Map<String, Integer> sortedMapInDescending = namesAges.entrySet() .stream() .sorted(Collections.reverseOrder(Entry.comparingByValue())) .collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue(), (entry1, entry2) -> entry2, LinkedHashMap::new)); // printing System.out.println("HashMap before sorting by value - " + namesAges); System.out.println("HashMap after sorting by value in descending order- " + sortedMapInDescending); } }
HashMap before sorting by value - {Hari=35, Jakey=50, Jhon=30, kane=45} HashMap after sorting by value in descending order- {Jakey=50, kane=45, Hari=35, Jhon=30}
// sorting using method ref // Descending Map<String, Integer> sortedMapInDescendingOrder = namesAges.entrySet() .stream() .sorted(Collections.reverseOrder(Entry.comparingByValue())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (entry1, entry2) -> entry2, LinkedHashMap::new)); // Ascending Map<String, Integer> sortedMapIAscendingOrder = namesAges.entrySet() .stream() .sorted(Collections.reverseOrder(Entry.comparingByValue())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (entry1, entry2) -> entry2, LinkedHashMap::new));
In this tutorial, We will learn the core differences between TreeMap and HashMap classes with example programs.
If you are new to java programming, suggest to go through the below topics.
In java, All Map implementations are to store the key-value pairs but there are few differences based on the implementations.
HashMap is extensively used in the day to day development from the collection framework when compared to TreeMap. Both uses internally bucketing concept but when any bucket partition becomes large the it does convert into TreeNode Structure.
The below are the common things in both classes. Let us look into those before understanding the differences.
2.1 HashMap and TreeMap classes implement Map<K,V>, Cloneable, Serializable interfaces and extends AbstractMap<K,V> class.
2.2 Both stores the values based on the keys. Always key and value should be provided.
2.3 Always key should be unique and if we add the same key again then old value will be replaced with the new value.
2.4 These are not synchronized.
2.5 Not thread-safe because if the original Map is modified during the iteration then it cause to throw runtime exception ConcurrentModificationException.
In the below example, we added few values to HashMap using put() method. Next, printed the all the values of HashMap.
Further tried to print the values using iterator and deleted the key "0333" from the original hashmap.
Removal key from hashmap produces the runtime exception.
package com.javaprogramto.collections.hashmap;
import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class HashMapExamples { public static void main(String[] args) { Map<String, String> hashMap = new HashMap<>(); hashMap.put("0111", "one's"); hashMap.put("0222", "two's"); hashMap.put("0333", "three's"); hashMap.put("0444", "four's"); hashMap.put("0111", "one's modified"); System.out.println("HashMap values are - " + hashMap); System.out.println("Iterating Hashmap and modifying the values"); Set<String> keys = hashMap.keySet(); Iterator<String> iterator = keys.iterator(); while (iterator.hasNext()) { String key = iterator.next(); System.out.println("key - " + key + ", value - " + hashMap.get(key)); if (key == "0333") { hashMap.remove(key); } } } }
Output:
HashMap values are - {0111=one's modified, 0222=two's, 0333=three's, 0444=four's} Iterating Hashmap and modifying the values key - 0111, value - one's modified key - 0222, value - two's key - 0333, value - three's Exception in thread "main" java.util.ConcurrentModificationException at java.base/java.util.HashMap$HashIterator.nextNode(HashMap.java:1490) at java.base/java.util.HashMap$KeyIterator.next(HashMap.java:1513) at com.javaprogramto.collections.hashmap.HashMapExamples.main(HashMapExamples.java:29)
In the below example, we added few values to TreeMap using put() method. Next, printed the all the values of TreeMap in sorted order.
Further tried to print the values using iterator and deleted the key "0333" from the original treemap.
Removal key from treemap produces the runtime exception.
package com.javaprogramto.collections.treemap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeMap; public class TreeMapExamples { public static void main(String[] args) { Map<String, String> treeMap = new TreeMap<>(); treeMap.put("0111", "one's"); treeMap.put("0222", "two's"); treeMap.put("0333", "three's"); treeMap.put("0444", "four's"); treeMap.put("0111", "one's modified"); System.out.println("treeMap values are - " + treeMap); System.out.println("Iterating treeMap and modifying the values"); Set<String> keys = treeMap.keySet(); Iterator<String> iterator = keys.iterator(); while (iterator.hasNext()) { String key = iterator.next(); System.out.println("key - " + key + ", value - " + treeMap.get(key)); if (key == "0333") { treeMap.remove(key); } } } }
Output:
treeMap values are - {0111=one's modified, 0222=two's, 0333=three's, 0444=four's} Iterating treeMap and modifying the values key - 0111, value - one's modified key - 0222, value - two's key - 0333, value - three's Exception in thread "main" java.util.ConcurrentModificationException at java.base/java.util.TreeMap$PrivateEntryIterator.nextEntry(TreeMap.java:1208) at java.base/java.util.TreeMap$KeyIterator.next(TreeMap.java:1262) at com.javaprogramto.collections.treemap.TreeMapExamples.main(TreeMapExamples.java:29)
The below are the main differences between these two maps.
5.1 TreeMap implements the NavigableMap interfaces rather than Map interface.
5.2 HashMap is implemented based on the hashtable
TreeMap is implemented based on Tree Structured based map such as Red Black Tree which is a balanced.
5.3 HashMap allows only one null key and multiple null values.
TreeMap does not allow null key but allows null values.
5.4 HashMap does not sort the keys where as TreeMap does sort the keys.
5.5 HashMap is faster then TreeMap because hashmap does not sort so it provides easy access to insertion and retrieval with constant time O(1) with put() and get() methods.
5.6 HashMap uses the equals() method for duplicate keys comparison but for TreeMap, keys are compared and sorted based on the compareTo() method. So, key must implement the Comparator or Comparable interface else will get the runtime error.
In this article, We've seen the first example programs on HashMap and TreeMap classes and next similarities and differences between HashMap and TreeMap.
package com.javaprogramto.collections.treemap; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeMap; public class TreeMapReverseTraversalExample { public static void main(String[] args) { // Creating the TreeMap object with reverse comparator using Collections.reverseOrder() Map<String, Integer> studentsCountMap = new TreeMap<>(Collections.reverseOrder()); // Adding students class and no of students in the class studentsCountMap.put("2nd class", 200); studentsCountMap.put("1nd class", 100); studentsCountMap.put("4nd class", 400); studentsCountMap.put("5nd class", 500); studentsCountMap.put("3nd class", 300); // Getting the Set object using keySet() method which returns the keys in the reverse order Set<String> keysSet = studentsCountMap.keySet(); // Getting the iterator object Iterator<String > it = keysSet.iterator(); // Iterating the map using regular method of iterator which retrieves the values in the reverse order. while (it.hasNext()) { String key = it.next(); System.out.println("Key - "+key+", Value - "+studentsCountMap.get(key)); } } }
Key - 5nd class, Value - 500 Key - 4nd class, Value - 400 Key - 3nd class, Value - 300 Key - 2nd class, Value - 200 Key - 1nd class, Value - 100
import java.util.Collections; import java.util.Iterator; import java.util.Set; import java.util.TreeMap; public class TreeMapReversedescendingkeySetExample { public static void main(String[] args) { // Creating the TreeMap object with default constructor TreeMap<String, Integer> studentsCountMap = new TreeMap<>(); // Adding students class and no of students in the class studentsCountMap.put("2nd class", 200); studentsCountMap.put("1nd class", 100); studentsCountMap.put("4nd class", 400); studentsCountMap.put("5nd class", 500); studentsCountMap.put("3nd class", 300); // Getting all keys as Set object using descendingKeySet() Set<String> keysSet = studentsCountMap.descendingKeySet(); // Getting the iterator object Iterator<String > it = keysSet.iterator(); // Iterating the map using regular method of iterator which retrieves the values in the reverse order. while (it.hasNext()) { String key = it.next(); System.out.println("Key - "+key+", Value - "+studentsCountMap.get(key)); } } }
Key - 5nd class, Value - 500 Key - 4nd class, Value - 400 Key - 3nd class, Value - 300 Key - 2nd class, Value - 200 Key - 1nd class, Value - 100
import java.util.Map; import java.util.TreeMap; public class TreeMapReversedescendingkeymapExample { public static void main(String[] args) { // Creating the TreeMap object with default constructor TreeMap<String, Integer> studentsCountMap = new TreeMap<>(); // Adding students class and no of students in the class studentsCountMap.put("2nd class", 200); studentsCountMap.put("1nd class", 100); studentsCountMap.put("4nd class", 400); studentsCountMap.put("5nd class", 500); studentsCountMap.put("3nd class", 300); // Getting all keys as Set object using descendingKeySet() Map<String, Integer> map = studentsCountMap.descendingMap(); map.forEach((key, value) -> System.out.println("Key - " + key + ", Value - " + value)); } }
package com.javaprogramto.collections.treemap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeMap; public class TreeMapIterate { public static void main(String[] args) { // Creating the TreeMap object Map<String, Integer> studentsCountMap = new TreeMap<>(); // Adding students class and no of students in the class studentsCountMap.put("2nd class", 200); studentsCountMap.put("1nd class", 100); studentsCountMap.put("4nd class", 400); studentsCountMap.put("5nd class", 500); studentsCountMap.put("3nd class", 300); // Getting the Set object using keySet() method Set<String> keysSet = studentsCountMap.keySet(); // Getting the iterator object Iterator<String > it = keysSet.iterator(); // Iterating the map using regular method of iterator. while (it.hasNext()) { String key = it.next(); System.out.println("Key - "+key+", Value - "+studentsCountMap.get(key)); } } }
Key - 1nd class, Value - 100 Key - 2nd class, Value - 200 Key - 3nd class, Value - 300 Key - 4nd class, Value - 400 Key - 5nd class, Value - 500
package com.javaprogramto.collections.treemap; import java.util.Map; import java.util.TreeMap; public class TreeMapIterateJava8 { public static void main(String[] args) { // Creating the TreeMap object Map<String, Integer> studentsCountMap = new TreeMap<>(); // Adding students class and no of students in the class studentsCountMap.put("2nd class", 200); studentsCountMap.put("1nd class", 100); studentsCountMap.put("4nd class", 400); studentsCountMap.put("5nd class", 500); studentsCountMap.put("3nd class", 300); // Java 8 lambda foreach studentsCountMap.forEach((key, value) -> { System.out.println("Key - " + key + ", Value - " + value); }); } }
package com.javaprogramto.collections.treemap; import java.util.Map; import java.util.TreeMap; public class TreeMapIterateJava8 { public static void main(String[] args) { // Creating the TreeMap object Map<String, Integer> studentsCountMap = new TreeMap<>(); // Adding students class and no of students in the class studentsCountMap.put("2nd class", 200); studentsCountMap.put("1nd class", 100); studentsCountMap.put("4nd class", 400); studentsCountMap.put("5nd class", 500); studentsCountMap.put("3nd class", 300); // java 8 Stream entry forEach studentsCountMap.entrySet().stream().forEach( entry -> System.out.println("entry key - " + entry.getKey() + ", entry value - " + entry.getValue())); } }
entry key - 1nd class, entry value - 100 entry key - 2nd class, entry value - 200 entry key - 3nd class, entry value - 300 entry key - 4nd class, entry value - 400 entry key - 5nd class, entry value - 500
In this tutorial, you'll learn what are the different ways to get the minimum and maximum value from unsorted List in java.
List may contains values type of integers or Strings or any custom objects. But let us understand with the simple data set such as list of integer values.
First, sort the list using Collections.sort() in ascending order. Next, take the first value as min and last value as max.
package com.javaprogramto.java8.sorting.list; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ListSortMinMaxExample { public static void main(String[] args) { // creating a list to store the integer values List<Integer> numbers = new ArrayList<>(); // adding integer values numbers.add(30); numbers.add(20); numbers.add(50); numbers.add(10); numbers.add(20); // sorting List using collections.sort() Collections.sort(numbers); // getting the min value int min = numbers.get(0); // getting max value int max = numbers.get(numbers.size() - 1); System.out.println("List sorting - min : " + min + ", max : " + max); } }
Output:
List sorting - min : 10, max : 50
Java Collections class has two methods to get the min and max values using Collections.max() and Collections.min() methods.
import java.util.Collections; public class ListCollectionsMinMaxExample { public static void main(String[] args) { // creating a list to store the integer values List<Integer> numbers = new ArrayList<>(); // adding integer values numbers.add(23); numbers.add(45); numbers.add(76); numbers.add(9); numbers.add(10); // getting the min value using min() method int min = Collections.min(numbers); // getting max value using max() method int max = Collections.max(numbers); System.out.println("List Collections api - min : " + min + ", max : " + max); } }
Output:
List Collections api - min : 9, max : 76
First create the max variable with first value in the list. Next, Iterate the list values and compare the max value with the next value. When max value is greater than next number, store the current number in the max variable else do nothing. Next, Compare the max value with the next number in the list. Repeat the same logic.
At the end, whatever the value present in the max variable is the highest value.
The same logic applies to get the min value. But, condition should be min value less than current number.
package com.javaprogramto.java8.sorting.list; import java.util.ArrayList; import java.util.List; public class ListNativeMinMaxExample { private static int getMinValue(List<Integer> numbers) { int min = Integer.MAX_VALUE; if (numbers.size() > 0) { for (Integer currentNumber : numbers) { if (min > currentNumber) { min = currentNumber; } } } return min; } private static int getMaxValue(List<Integer> numbers) { int max = Integer.MIN_VALUE; if (numbers.size() > 0) { for (Integer currentNumber : numbers) { if (max < currentNumber) { max = currentNumber; } } } return max; } public static void main(String[] args) { // creating a list to store the integer values List<Integer> numbers = new ArrayList<>(); // adding integer values numbers.add(23); numbers.add(45); numbers.add(76); numbers.add(9); numbers.add(10); // getting the min value using min() method int min = getMinValue(numbers); // getting max value using max() method int max = getMaxValue(numbers); System.out.println("Native method - min : " + min + ", max : " + max); } }
Output:
Native method - min : 9, max : 76
Time complexity is O(n).
In this article, you've seen the 3 different ways to get the min and max value from list in java.
GitHub
Read Next
Collections.sort() and Custom Objects
How to find the largest value from array in java ?
In this article, You're going to learn how to convert ArrayList to String[] Array in Java. ArrayList is used to store the List of String using the toArray() and Stream API toArray() method.