Java Tutorial
- Java - Home
- Java - Overview
- Java - History
- Java - Features
- Java vs C++
- Java Virtual Machine(JVM)
- Java - JDK vs JRE vs JVM
- Java - Hello World Program
- Java - Environment Setup
- Java - Basic Syntax
- Java - Variable Types
- Java - Data Types
- Java - Type Casting
- Java - Unicode System
- Java - Basic Operators
- Java - Comments
- Java - User Input
Java Control Statements
- Java - Loop Control
- Java - Decision Making
- Java - If-else
- Java - Switch
- Java - For Loops
- Java - For-Each Loops
- Java - While Loops
- Java - do-while Loops
- Java - Break
- Java - Continue
Object Oriented Programming
- Java - OOPs Concepts
- Java - Object & Classes
- Java - Class Attributes
- Java - Class Methods
- Java - Methods
- Java - Variables Scope
- Java - Constructors
- Java - Access Modifiers
- Java - Inheritance
- Java - Aggregation
- Java - Polymorphism
- Java - Overriding
- Java - Method Overloading
- Java - Dynamic Binding
- Java - Static Binding
- Java - Instance Initializer Block
- Java - Abstraction
- Java - Encapsulation
- Java - Interfaces
- Java - Packages
- Java - Inner Classes
- Java - Static Class
- Java - Anonymous Class
- Java - Singleton Class
- Java - Wrapper Classes
- Java - Enums
- Java - Enum Constructor
- Java - Enum Strings
Java Built-in Classes
- Java - Number
- Java - Boolean
- Java - Characters
- Java - Strings
- Java - Arrays
- Java - Date & Time
- Java - Math Class
Java File Handling
- Java - Files
- Java - Create a File
- Java - Write to File
- Java - Read Files
- Java - Delete Files
- Java - Directories
- Java - I/O Streams
Java Error & Exceptions
- Java - Exceptions
- Java - try-catch Block
- Java - try-with-resources
- Java - Multi-catch Block
- Java - Nested try Block
- Java - Finally Block
- Java - throw Exception
- Java - Exception Propagation
- Java - Built-in Exceptions
- Java - Custom Exception
Java Multithreading
- Java - Multithreading
- Java - Thread Life Cycle
- Java - Creating a Thread
- Java - Starting a Thread
- Java - Joining Threads
- Java - Naming Thread
- Java - Thread Scheduler
- Java - Thread Pools
- Java - Main Thread
- Java - Thread Priority
- Java - Daemon Threads
- Java - Thread Group
- Java - Shutdown Hook
Java Synchronization
- Java - Synchronization
- Java - Block Synchronization
- Java - Static Synchronization
- Java - Inter-thread Communication
- Java - Thread Deadlock
- Java - Interrupting a Thread
- Java - Thread Control
- Java - Reentrant Monitor
Java Networking
- Java - Networking
- Java - Socket Programming
- Java - URL Processing
- Java - URL Class
- Java - URLConnection Class
- Java - HttpURLConnection Class
- Java - Socket Class
- Java - Generics
Java Collections
Java List Interface
Java Queue Interface
Java Map Interface
- Java - Map Interface
- Java - HashMap
- Java - LinkedHashMap
- Java - WeakHashMap
- Java - EnumMap
- Java - SortedMap Interface
- Java - TreeMap
- Java - The IdentityHashMap Class
Java Set Interface
- Java - Set Interface
- Java - HashSet
- Java - EnumSet
- Java - LinkedHashSet
- Java - SortedSet Interface
- Java - TreeSet
Java Data Structures
- Java - Data Structures
- Java - Enumeration
- Java - BitSet Class
- Java - Dictionary
- Java - Hashtable
- Java - Properties
Java Collections Algorithms
Advanced Java
- Java - Command-Line Arguments
- Java - Lambda Expressions
- Java - Sending Email
- Java - Applet Basics
- Java - Javadoc Comments
- Java - Autoboxing and Unboxing
- Java - File Mismatch Method
- Java - REPL (JShell)
- Java - Multi-Release Jar Files
- Java - Private Interface Methods
- Java - Inner Class Diamond Operator
- Java - Multiresolution Image API
- Java - Collection Factory Methods
- Java - Module System
- Java - Nashorn JavaScript
- Java - Optional Class
- Java - Method References
- Java - Functional Interfaces
- Java - Default Methods
- Java - Base64 Encode Decode
- Java - Switch Expressions
- Java - Teeing Collectors
- Java - Microbenchmark
- Java - Text Blocks
- Java - Null Pointer Exception
- Java - Packaging Tools
- Java - Sealed Classes
- Java - Record Classes
- Java - Hidden Classes
- Java - Compact Number Formatting
Java Miscellaneous
- Java - Recursion
- Java - Regular Expressions
- Java - Serialization
- Java - Strings
- Java - Process API Improvements
- Java - Stream API Improvements
- Java - Enhanced @Deprecated Annotation
- Java - CompletableFuture API Improvements
- Java - Array Methods
- Java - Streams
- Java - Datetime Api
- Java 8 - New Features
- Java 9 - New Features
Java APIs & Frameworks
Java Useful Resources
Java - The Collection Algorithms
The collections framework defines several algorithms that can be applied to collections and maps.
These algorithms are defined as static methods within the Collections class. Several of the methods can throw a ClassCastException, which occurs when an attempt is made to compare incompatible types, or an UnsupportedOperationException, which occurs when an attempt is made to modify an unmodifiable collection.
The methods defined in collection framework's algorithm are summarized in the following table −
Sr.No. | Method & Description |
---|---|
1 | static int binarySearch(List list, Object value, Comparator c) Searches for value in the list ordered according to c. Returns the position of value in list, or -1 if value is not found. |
2 | static int binarySearch(List list, Object value) Searches for value in the list. The list must be sorted. Returns the position of value in list, or -1 if value is not found. |
3 | static void copy(List list1, List list2) Copies the elements of list2 to list1. |
4 | static Enumeration enumeration(Collection c) Returns an enumeration over c. |
5 | static void fill(List list, Object obj) Assigns obj to each element of the list. |
6 | static int indexOfSubList(List list, List subList) Searches list for the first occurrence of subList. Returns the index of the first match, or .1 if no match is found. |
7 | static int lastIndexOfSubList(List list, List subList) Searches list for the last occurrence of subList. Returns the index of the last match, or .1 if no match is found. |
8 | static ArrayList list(Enumeration enum) Returns an ArrayList that contains the elements of enum. |
9 | static Object max(Collection c, Comparator comp) Returns the maximum element in c as determined by comp. |
10 | static Object max(Collection c) Returns the maximum element in c as determined by natural ordering. The collection need not be sorted. |
11 | static Object min(Collection c, Comparator comp) Returns the minimum element in c as determined by comp. The collection need not be sorted. |
12 | static Object min(Collection c) Returns the minimum element in c as determined by natural ordering. |
13 | static List nCopies(int num, Object obj) Returns num copies of obj contained in an immutable list. num must be greater than or equal to zero. |
14 | static boolean replaceAll(List list, Object old, Object new) Replaces all occurrences of old with new in the list. Returns true if at least one replacement occurred. Returns false, otherwise. |
15 | static void reverse(List list) Reverses the sequence in list. |
16 | static Comparator reverseOrder( ) Returns a reverse comparator. |
17 | static void rotate(List list, int n) Rotates list by n places to the right. To rotate left, use a negative value for n. |
18 | static void shuffle(List list, Random r) Shuffles (i.e., randomizes) the elements in the list by using r as a source of random numbers. |
19 | static void shuffle(List list) Shuffles (i.e., randomizes) the elements in list. |
20 | static Set singleton(Object obj) Returns obj as an immutable set. This is an easy way to convert a single object into a set. |
21 | static List singletonList(Object obj) Returns obj as an immutable list. This is an easy way to convert a single object into a list. |
22 | static Map singletonMap(Object k, Object v) Returns the key/value pair k/v as an immutable map. This is an easy way to convert a single key/value pair into a map. |
23 | static void sort(List list, Comparator comp) Sorts the elements of list as determined by comp. |
24 | static void sort(List list) Sorts the elements of the list as determined by their natural ordering. |
25 | static void swap(List list, int idx1, int idx2) Exchanges the elements in the list at the indices specified by idx1 and idx2. |
26 | static Collection synchronizedCollection(Collection c) Returns a thread-safe collection backed by c. |
27 | static List synchronizedList(List list) Returns a thread-safe list backed by list. |
28 | static Map synchronizedMap(Map m) Returns a thread-safe map backed by m. |
29 | static Set synchronizedSet(Set s) Returns a thread-safe set backed by s. |
30 | static SortedMap synchronizedSortedMap(SortedMap sm) Returns a thread-safe sorted set backed by sm. |
31 | static SortedSet synchronizedSortedSet(SortedSet ss) Returns a thread-safe set backed by ss. |
32 | static Collection unmodifiableCollection(Collection c) Returns an unmodifiable collection backed by c. |
33 | static List unmodifiableList(List list) Returns an unmodifiable list backed by the list. |
34 | static Map unmodifiableMap(Map m) Returns an unmodifiable map backed by m. |
35 | static Set unmodifiableSet(Set s) Returns an unmodifiable set backed by s. |
36 | static SortedMap unmodifiableSortedMap(SortedMap sm) Returns an unmodifiable sorted map backed by sm. |
37 | static SortedSet unmodifiableSortedSet(SortedSet ss) Returns an unmodifiable sorted set backed by ss. |
Example 1
Following is an example, which demonstrates various algorithms using LinkedList to add elements and sort its elements in reverse order. Using iterator, list is iterated then shuffled and lastly minimum and maximum values are retrieved and printed.
import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class AlgorithmsDemo { public static void main(String args[]) { // Create and initialize linked list List<Integer< ll = new LinkedList<<(); ll.add(Integer.valueOf(-8)); ll.add(Integer.valueOf(20)); ll.add(Integer.valueOf(-20)); ll.add(Integer.valueOf(8)); // Create a reverse order comparator Comparator<Integer< r = Collections.reverseOrder(); // Sort list by using the comparator Collections.sort(ll, r); // Get iterator Iterator<Integer< li = ll.iterator(); System.out.print("List sorted in reverse: "); while(li.hasNext()) { System.out.print(li.next() + " "); } System.out.println(); } }
Output
List sorted in reverse: 20 8 -8 -20
Example 2
Following is an example, which demonstrates various algorithms using LinkedList to add elements and sort its elements in natural order. Using iterator, list is iterated then shuffled and lastly minimum and maximum values are retrieved and printed.
import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class AlgorithmsDemo { public static void main(String args[]) { // Create and initialize linked list List<Integer> ll = new LinkedList<>(); ll.add(Integer.valueOf(-8)); ll.add(Integer.valueOf(20)); ll.add(Integer.valueOf(-20)); ll.add(Integer.valueOf(8)); // Sort list by using the default comparator Collections.sort(ll); // Get iterator Iterator<Integer> li = ll.iterator(); System.out.print("List sorted: "); while(li.hasNext()) { System.out.print(li.next() + " "); } System.out.println(); Collections.shuffle(ll); // display randomized list li = ll.iterator(); System.out.print("List shuffled: "); while(li.hasNext()) { System.out.print(li.next() + " "); } System.out.println(); System.out.println("Minimum: " + Collections.min(ll)); System.out.println("Maximum: " + Collections.max(ll)); } }
Output
List sorted: -20 -8 8 20 List shuffled: -20 -8 20 8 Minimum: -20 Maximum: 20
Example 3
Following is an example, which demonstrates various algorithms using LinkedList to add String elements and sort its elements in natural order. List is printed then shuffled and lastly minimum and maximum values are retrieved and printed.
import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class AlgorithmsDemo { public static void main(String args[]) { // Create and initialize linked list List<String> list = new LinkedList<>(); list.add("Ram"); list.add("Mohan"); list.add("Julie"); list.add("Raheem"); // Sort list by using the default comparator Collections.sort(list); // print the sorted list System.out.println("Sorted List: " + list); // shuffle the list Collections.shuffle(list); // print the shuffled list System.out.println("Shuffled List: " + list); System.out.println("Minimum: " + Collections.min(list)); System.out.println("Maximum: " + Collections.max(list)); } }
Output
Sorted List: [Julie, Mohan, Raheem, Ram] Shuffled List: [Mohan, Raheem, Julie, Ram] Minimum: Julie Maximum: Ram
To Continue Learning Please Login
Login with Google