Java – Garbage Collection ”; Previous Next The lifecycle of a Java object is managed by the JVM. Once an object is created by the programmer, we need not worry about the rest of its lifecycle. The JVM will automatically find those objects that are not in use anymore and reclaim their memory from the heap. What is Java Garbage Collection? Garbage collection is a major operation that JVM does and tuning it for our needs can give massive performance boosts to our application. There are a variety of garbage collection algorithms that are provided by modern JVMs. We need to be aware of our application”s needs to decide on which algorithm to use. You cannot deallocate an object programmatically in Java as you can do in non-GC languages like C and C++. Therefore, you cannot have dangling references in Java. However, you may have null references (references that refer to an area of memory where the JVM won”t ever store objects). Whenever a null reference is used, the JVM throws a NullPointerException. Note that while it is rare to find memory leaks in Java programs thanks to the GC, they do happen. We will create a memory leak at the end of this chapter. Types of Garbage Collectors The following GCs are used in modern JVMs Serial collector Throughput collector CMS collector G1 collector Each of the above algorithms does the same task – finding objects that are no longer in use and reclaiming the memory that they occupy in the heap. One of the naïve approaches to this would be to count the number of references that each object has and free it up as soon as the number of references turn 0 (this is also known as reference counting). Why is this naïve? Consider a circular linked list. Each of its nodes will have a reference to it, but the entire object is not being referenced from anywhere, and should be freed, ideally. Memory Coalescing The JVM not only frees the memory, but also coalesces small memory chucks into bigger ones it. This is done to prevent memory fragmentation. On a simple note, a typical GC algorithm does the following activities − Finding unused objects Freeing the memory that they occupy in the heap Coalescing the fragments The GC has to stop application threads while it is running. This is because it moves the objects around when it runs, and therefore, those objects cannot be used. Such stops are called “stop-the-world” pauses and minimizing the frequency and duration of these pauses is what we aim while tuning our GC. A simple demonstration of memory coalescing is shown below: The shaded portion are objects that need to be freed. Even after when all the space is reclaimed, we can only allocate an object of maximum size = 75Kb. This is even after we have 200Kb of free space as shown below: Generations in Garbage Collection Most JVMs divide the heap into three generations − the young generation (YG), the old generation (OG) and permanent generation (also called tenured generation). We shall look into a simple example. The String class in Java is immutable. This means that every time you need to change the contents of a String object, you have to create a new object altogether. Let us suppose you make changes to the string 1000 times in a loop as shown in the below code − String str = “G11 GC”; for(int i = 0 ; i < 1000; i++) { str = str + String.valueOf(i); } In each loop, we create a new string object, and the string created during the previous iteration becomes useless (that is, it is not referenced by any reference). T lifetime of that object was just one iteration – they”ll be collected by the GC in no time. Such short-lived objects are kept in the young generation area of the heap. The process of collecting objects from the young generation is called minor garbage collection, and it always causes a “stop-the-world” pause. Minor Garbage Collection As the young generation gets filled up, the GC does a minor garbage collection. Dead objects are discarded, and live objects are moved to the old generation. The application threads stop during this process. Here, we can see the advantages that such a generation design offers. The young generation is only a small part of the heap and gets filled up quickly. But processing it takes a lot lesser time than the time taken to process the entire heap. So, the “stop-the-world” pauses in this case are much shorter, although more frequent. We should always aim for shorter pauses over longer ones, even though they might be more frequent. Full Garbage Collection The young generation is divided into two spaces − eden and survivor space. Objects that have survived during the collection of eden are moved to survivor space, and those who survive the survivor space are moved to the old generation. The young generation is compacted while it is collected. As objects are moved to the old generation, it fills up eventually, and has to be collected and compacted. Different algorithms take different approaches to this. Some of them stop the application threads (which leads to a long “stop-the-world” pause since the old generation is quite big in comparison to the young generation), while some of them do it concurrently while the application threads keep running. This process is called full GC. Two such collectors are CMS and G1. Tuning Garbage Collectors We can tune Garbage collectors as well as per our need. Following are the areas which we can configure based on the situations: Heap Size Allocation Generation Sizes Allocation Permagen and Metaspace Configurations Let”s understand each in detail while understanding their impact. We”ll also discuss the recommendations based on available memory, CPU configurations and other relevant factors. Heap Size Allocation The heap size is an important factor in the performance of our Java applications. If it is too small, then
Category: Java
Java – TreeSet
Java TreeSet Class ”; Previous Next Introduction The Java TreeSet class implements the Set interface. Following are the important points about TreeSet − The TreeSet class guarantees that the Map will be in ascending key order and backed by a TreeMap. The Map is sorted according to the natural sort method for the key Class, or by the Comparator provided at set creation time, that will depend on which constructor used. The ordering must be total in order for the Tree to function properly. Class declaration Following is the declaration for java.util.TreeSet class − public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable, Serializable Parameters Following is the parameter for java.util.TreeSet class − E − This is the type of elements maintained by this set. Class constructors Sr.No. Constructor & Description 1 TreeSet() This constructor constructs a new, empty tree set, sorted according to the natural ordering of its elements. 2 TreeSet(Collection<? extends E> c) This constructor constructs a new tree set containing the elements in the specified collection, sorted according to the natural ordering of its elements. 3 TreeSet(Comparator<? super E> comparator) This constructor constructs a new, empty tree set, sorted according to the specified comparator. 4 TreeSet(SortedSet<E> s) This constructor constructs a new tree set containing the same elements and using the same ordering as the specified sorted set. Class methods Sr.No. Method & Description 1 boolean add(E e) This method adds the specified element to this set if it is not already present. 2 boolean addAll(Collection<? extends E> c) This method adds all of the elements in the specified collection to this set. 3 E ceiling(E e) This method returns the least element in this set greater than or equal to the given element, or null if there is no such element. 4 void clear() This method removes all of the elements from this set. 5 Object clone() This method returns a shallow copy of this TreeSet instance. 6 boolean contains(Object o) This method returns true if this set contains the specified element. 7 Iterator<E> descendingIterator() This method returns an iterator over the elements in this set in descending order. 8 NavigableSet<E> descendingSet() This method returns a reverse order view of the elements contained in this set. 9 E first() This method returns the first (lowest) element currently in this set. 10 E floor(E e) This method Returns the greatest element in this set less than or equal to the given element, or null if there is no such element. 11 SortedSet<E> headSet(E toElement) This method returns a view of the portion of this set whose elements are strictly less than toElement. 12 E higher(E e) This method returns the least element in this set strictly greater than the given element, or null if there is no such element. 13 boolean isEmpty() This method returns true if this set contains no elements. 14 Iterator<E> iterator() This method returns an iterator over the elements in this set in ascending order. 15 E last() This method returns the last (highest) element currently in this set. 16 E lower(E e) This method returns the greatest element in this set strictly less than the given element, or null if there is no such element. 17 E pollFirst() This method retrieves and removes the first (lowest) element, or returns null if this set is empty. 18 E pollLast() This method retrieves and removes the last (highest) element, or returns null if this set is empty. 19 boolean remove(Object o) This method removes the specified element from this set if it is present. 20 int size() This method returns the number of elements in this set (its cardinality). 21 Spliterator<E> spliterator() Creates a late-binding and fail-fast Spliterator over the elements in this set. 22 SortedSet<E> subSet(E fromElement, E toElement) This method returns a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive. 23 SortedSet<E> tailSet(E fromElement) This method returns a view of the portion of this set whose elements are greater than or equal to fromElement. Methods inherited This class inherits methods from the following classes − java.util.AbstractSet java.util.AbstractCollection java.util.Object java.util.Set Adding Entries to a TreeSet Example The following example shows the usage of Java TreeSet add() method to add entries to the treeset. We”ve created a TreeSet object of Integer. Then few entries are added using add() method and treeset object is printed to check its content. package com.tutorialspoint; import java.util.TreeSet; public class TreeSetDemo { public static void main(String[] args) { // creating a TreeSet TreeSet<Integer> treeset = new TreeSet<>(); // adding in the tree set treeset.add(12); treeset.add(13); treeset.add(14); treeset.add(15); // displaying the Tree set data System.out.print(“Tree set : ” + treeset); } } Output Let us compile and run the above program, this will produce the following result. Tree set : [12, 13, 14, 15] Print Page Previous Next Advertisements ”;
Java – EnumMap
Java EnumMap Class ”; Previous Next Introduction The Java EnumMap class is a specialized Map implementation for use with enum keys.Following are the important points about EnumMap − All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created. Enum maps are maintained in the natural order of their keys. EnumMap is not synchronized.If multiple threads access an enum map concurrently, and at least one of the threads modifies the map, it should be synchronized externally. Class declaration Following is the declaration for java.util.EnumMap class − public class EnumMap<K extends Enum<K>,V> extends AbstractMap<K,V> implements Serializable, Cloneable Class constructors Sr.No. Constructor & Description 1 EnumMap(Class<K> keyType) This constructor creates an empty enum map with the specified key type. 2 EnumMap(EnumMap<K,? extends V> m) This constructor creates an enum map with the same key type as the specified enum map, initially containing the same mappings (if any). 3 EnumMap(Map<K,? extends V> m) This constructor creates an enum map initialized from the specified map. Class methods Sr.No. Method & Description 1 void clear() This method removes all mappings from this map. 2 EnumMap<K,V> clone() This method returns a shallow copy of this enum map. 3 boolean containsKey(Object key) This method returns true if this map contains a mapping for the specified key. 4 boolean containsValue(Object value) This method returns true if this map maps one or more keys to the specified value. 5 Set<Map.Entry<K,V>> entrySet() This method returns a Set view of the mappings contained in this map. 6 boolean equals(Object o) This method compares the specified object with this map for equality. 7 V get(Object key) This method returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. 8 int hashCode() This method returns the hash code value for this map. 9 Set<K> keySet() This method returns a Set view of the keys contained in this map. 10 V put(K key, V value) This method associates the specified value with the specified key in this map. 11 void putAll(Map<? extends K,? extends V> m) This method Copies all of the mappings from the specified map to this map. 12 V remove(Object key) This method removes the mapping for this key from this map if present. 13 int size() This method returns the number of key-value mappings in this map. 14 Collection<V> values() This method returns a Collection view of the values contained in this map. Methods inherited This class inherits methods from the following classes − java.util.AbstractMap java.util.Object Adding a Key-Value to an EnumMap Of Enum, Integer Pair Example The following example shows the usage of Java EnumMap put(K,V) method to put a value in the EnumMap instance. We”ve created a enum Numbers. Then EnumMap is created of enum Numbers and Integer. Few entries are added using put(K,V) and enumMap is printed. Using put() method again, a value of enumMap is replaced and map is printed again. package com.tutorialspoint; import java.util.EnumMap; public class EnumMapDemo { // create an enum public enum Numbers{ONE, TWO, THREE, FOUR, FIVE}; public static void main(String[] args) { EnumMap<Numbers,Integer> map = new EnumMap<>(Numbers.class); // associate values in map map.put(Numbers.ONE, 1); map.put(Numbers.TWO, 2); map.put(Numbers.THREE,3); // print the whole map System.out.println(map); map.put(Numbers.THREE, 4); // print the updated map System.out.println(map); } } Let us compile and run the above program, this will produce the following result − {ONE=1, TWO=2, THREE=3} {ONE=1, TWO=2, THREE=4} Print Page Previous Next Advertisements ”;
Java – Collection
Java Collections Class ”; Previous Next Introduction The Java Collections class consists exclusively of static methods that operate on or return collections.Following are the important points about Collections − It contains polymorphic algorithms that operate on collections, “wrappers”, which return a new collection backed by a specified collection. The methods of this class all throw a NullPointerException if the collections or class objects provided to them are null. Class declaration Following is the declaration for java.util.Collections class − public class Collections extends Object Field Following are the fields for java.util.Collections class − static List EMPTY_LIST − This is the empty list (immutable). static Map EMPTY_MAP − This is the empty map (immutable). static Set EMPTY_SET − This is the empty set (immutable). Class methods Sr.No. Method & Description 1 static <T> boolean addAll(Collection<? super T> c, T… elements) This method adds all of the specified elements to the specified collection. 2 static <T> Queue<T> asLifoQueue(Deque<T> deque) This method returns a view of a Deque as a Last-in-first-out (Lifo) Queue. 3 static <T> int binarySearch(List<? extends Comparable<? super T>> list, T key) This method searches the specified list for the specified object using the binary search algorithm. 4 static <E> Collection<E> checkedCollection(Collection<E> c, Class<E> type) This method returns a dynamically typesafe view of the specified collection. 5 static <E> List<E> checkedList(List<E> list, Class<E> type) This method returns a dynamically typesafe view of the specified list. 6 static <K,V> Map<K,V> checkedMap(Map<K,V> m, Class<K> keyType, Class<V> valueType) This method returns a dynamically typesafe view of the specified map. 7 static <K,V> Navigable<K,V> checkedNavigableMap(Navigable<K,V> m, Class<K> keyType, Class<V> valueType) This method returns a dynamically typesafe view of the specified navigable map. 8 static <E> NavigableSet<E> checkedNavigableSet(NavigableSet<E> s, Class<E> type) This method returns a dynamically typesafe view of the specified navigable set. 9 static <E> Queue<E> checkedQueue(Queue<E> s, Class<E> type) This method returns a dynamically typesafe view of the specified queue. 10 static <E> Set<E> checkedSet(Set<E> s, Class<E> type) This method returns a dynamically typesafe view of the specified set. 11 static <K,V> SortedMap<K,V> checkedSortedMap(SortedMap<K,V> m, Class<K> keyType, Class<V> valueType) This method returns a dynamically typesafe view of the specified sorted map. 12 static <E> SortedSet<E>checkedSortedSet(SortedSet<E> s, Class<E> type) This method returns a dynamically typesafe view of the specified sorted set. 13 static <T> void copy(List<? super T> dest, List<? extends T> src) This method copies all of the elements from one list into another. 14 static boolean disjoint(Collection<?> c1, Collection<?> c2) This method returns true if the two specified collections have no elements in common. 15 static <T> Enumeration <T> emptyEnumeration() This method returns the empty enumeration. 16 static <T> Iterator <T> emptyIterator() This method returns the empty iterator. 17 static <T> List<T> emptyList() This method returns the empty list (immutable). 18 static <T> ListIterator <T> emptyListIterator() This method returns the empty list iterator. 19 static <K,V> Map<K,V> emptyMap() This method returns the empty map (immutable). 20 static <K,V> NavigableMap<K,V> emptyNavigableMap() This method returns the empty navigable map (immutable). 21 static <T> NavigableSet<T> emptyNavigableSet() This method returns the empty navigable set (immutable). 22 static <T> Set<T> emptySet() This method returns the empty set (immutable). 23 static <K,V> SortedMap<K,V> emptySortedMap() This method returns the empty sorted map (immutable). 24 static <T> SortedSet<T> emptySortedSet() This method returns the empty sorted set (immutable). 25 static <T> Enumeration<T> enumeration(Collection<T> c) This method returns an enumeration over the specified collection. 26 static <T> void fill(List<? super T> list, T obj) This method replaces all of the elements of the specified list with the specified element. 27 static int frequency(Collection<?> c, Object o) This method returns the number of elements in the specified collection equal to the specified object. 28 static int indexOfSubList(List<?> source, List<?> target) This method returns the starting position of the first occurrence of the specified target list within the specified source list, or -1 if there is no such occurrence. 29 static int lastIndexOfSubList(List<?> source, List<?> target) This method returns the starting position of the last occurrence of the specified target list within the specified source list, or -1 if there is no such occurrence. 30 static <T> ArrayList<T> list(Enumeration<T> e) This method returns an array list containing the elements returned by the specified enumeration in the order they are returned by the enumeration. 31 static <T extends Object & Comparable<? super T> >T max(Collection<? extends T> coll) This method returns the maximum element of the given collection, according to the natural ordering of its elements. 32 static <T extends Object & Comparable<? super T>>T min(Collection<? extends T> coll) This method Returns the minimum element of the given collection, according to the natural ordering of its elements. 33 static <T> List<T> nCopies(int n, T o) This method returns an immutable list consisting of n copies of the specified object. 34 static <E> Set<E> newSetFromMap(Map<E,Boolean> map) This method returns a set backed by the specified map. 35 static <T> boolean replaceAll(List<T> list, T oldVal, T newVal) This method replaces all occurrences of one specified value in a list with another. 36 static void reverse(List<?> list) This method reverses the order of the elements in the specified list. 37 static <T> Comparator<T> reverseOrder() This method returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface. 38 static void rotate(List<?> list, int distance) This method rotates the elements in the specified list by the specified distance. 39 static void shuffle(List<?> list) This method randomly permutes the specified list using a default source of randomness. 40 static <T> Set<T> singleton(T o) This method returns an immutable set containing only the specified object. 41 static <T> List<T> singletonList(T o) This method returns an immutable list containing only the specified object. 42 static <K,V> Map<K,V> singletonMap(K key, V value) This method returns an immutable map, mapping only the specified key to the specified value. 43 static <T extends Comparable<? super T>> void sort(List<T> list) This method sorts the specified list into ascending order, according to the natural
Java – IdentityHashMap
Java IdentityHashMap Class ”; Previous Next Introduction The Java IdentityHashMap class implements the Map interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values).Following are the important points about IdentityHashMap − This class provides all of the optional map operations, and permits null values and the null key. This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time. In an IdentityHashMap, two keys k1 and k2 are considered equal if and only if (k1==k2), while in Map implementations (like HashMap) two keys k1 and k2 are considered equal if and only if (k1==null ? k2==null : k1.equals(k2)). Class declaration Following is the declaration for java.util.IdentityHashMap class − public class IdentityHashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Serializable, Cloneable Class constructors Sr.No. Constructor & Description 1 IdentityHashMap() This constructs a new, empty identity hash map with a default expected maximum size (21). 2 IdentityHashMap(int expectedMaxSize) This constructs a new, empty map with the specified expected maximum size. 3 IdentityHashMap(Map<? extends K,? extends V> m) This constructs a new identity hash map containing the keys-value mappings in the specified map. Class methods Sr.No. Method & Description 1 void clear() This method removes all of the mappings from this map. 2 Object clone() This method returns a shallow copy of this identity hash map: the keys and values themselves are not cloned. 3 boolean containsKey(Object key) This method tests whether the specified object reference is a key in this identity hash map. 4 boolean containsValue(Object value) This method tests whether the specified object reference is a value in this identity hash map. 5 Set<Map.Entry<K,V>> entrySet() This method returns a Set view of the mappings contained in this map. 6 boolean equals(Object o) This method compares the specified object with this map for equality. 7 V get(Object key) This method returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. 8 int hashCode() This method returns returns the hash code value for this map. 9 boolean isEmpty() This method returns true if this identity hash map contains no key-value mappings. 10 Set<K> keySet() This method returns an identity-based set view of the keys contained in this map. 11 V put(K key, V value) This method associates the specified value with the specified key in this identity hash map. 12 void putAll(Map<? extends K,? extends V> m) This method copies all of the mappings from the specified map to this map. 13 V remove(Object key) This method removes the mapping for this key from this map if present. 14 int size() This method returns the number of key-value mappings in this identity hash map. 15 Collection<V> values() This method returns returns a Collection view of the values contained in this map. Methods inherited This class inherits methods from the following classes − java.util.AbstractMap java.util.Object Adding a Key-Value Mapping in an IdentityHashMap Example The following example shows the usage of Java IdentityHashMap put() method to put few values in a Map. We”ve created a Map object of Integer,Integer. Then few entries are added using put() method and then map is printed. package com.tutorialspoint; import java.util.IdentityHashMap; public class IdentityHashMapDemo { public static void main(String args[]) { // create identity map IdentityHashMap<Integer,Integer> newmap = new IdentityHashMap<>(); // populate identity map newmap.put(1, 1); newmap.put(2, 2); newmap.put(3, 3); System.out.println(“Map elements: ” + newmap); } } Let us compile and run the above program, this will produce the following result. Map elements: {2=2, 3=3, 1=1} Print Page Previous Next Advertisements ”;
Java – Scanner
Java Scanner Class ”; Previous Next Introduction The Java Scanner class is a simple text scanner which can parse primitive types and strings using regular expressions.Following are the important points about Scanner − A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. A scanning operation may block waiting for input. A Scanner is not safe for multithreaded use without external synchronization. Class declaration Following is the declaration for java.util.Scanner class − public final class Scanner extends Object implements Iterator<String> Class constructors Sr.No. Constructor & Description 1 Scanner(File source) This constructs a new Scanner that produces values scanned from the specified file. 2 Scanner(File source, String charsetName) This constructs a new Scanner that produces values scanned from the specified file. 3 Scanner(File source, Charset charset) This constructs a new Scanner that produces values scanned from the specified file. 4 Scanner(InputStream source) This constructs a new Scanner that produces values scanned from the specified input stream. 5 Scanner(InputStream source, String charsetName) This constructs a new Scanner that produces values scanned from the specified input stream. 6 Scanner(InputStream source, Charset charset) This constructs a new Scanner that produces values scanned from the specified input stream. 7 Scanner(Readable source) This constructs a new Scanner that produces values scanned from the specified source. 8 Scanner(String source) This constructs a new Scanner that produces values scanned from the specified source. 9 Scanner(ReadableByteChannel source) This constructs a new Scanner that produces values scanned from the specified channel. 10 Scanner(ReadableByteChannel source, String charsetName) This constructs a new Scanner that produces values scanned from the specified channel. 11 Scanner(ReadableByteChannel source, Charset charset) This constructs a new Scanner that produces values scanned from the specified channel. 12 Scanner(Path source) This constructs a new Scanner that produces values scanned from the specified file. 13 Scanner(Path source, String charsetName) This constructs a new Scanner that produces values scanned from the specified file. 14 Scanner(Path source, Charset charset) This constructs a new Scanner that produces values scanned from the specified file. Class methods Sr.No. Method & Description 1 void close() This method closes this scanner. 2 Pattern delimiter() This method returns the Pattern this Scanner is currently using to match delimiters. 3 Stream<MatchResult> findAll(String patString) This method returns a stream of match results that match the provided pattern string. 4 String findInLine(Pattern pattern) This method attempts to find the next occurrence of the specified pattern ignoring delimiters. 5 String findWithinHorizon(Pattern pattern, int horizon) This method attempts to find the next occurrence of the specified pattern. 6 boolean hasNext() This method returns true if this scanner has another token in its input. 7 boolean hasNextBigDecimal() This method returns true if the next token in this scanner”s input can be interpreted as a BigDecimal using the nextBigDecimal() method. 8 boolean hasNextBigInteger() This method returns true if the next token in this scanner”s input can be interpreted as a BigInteger in the default radix using the nextBigInteger() method. 9 boolean hasNextBoolean() This method returns true if the next token in this scanner”s input can be interpreted as a boolean value using a case insensitive pattern created from the string “true|false”. 10 boolean hasNextByte() This method returns true if the next token in this scanner”s input can be interpreted as a byte value in the default radix using the nextByte() method. 11 boolean hasNextDouble() This method returns true if the next token in this scanner”s input can be interpreted as a double value using the nextDouble() method. 12 boolean hasNextFloat() This method Returns true if the next token in this scanner”s input can be interpreted as a float value using the nextFloat() method. 13 boolean hasNextInt() This method returns true if the next token in this scanner”s input can be interpreted as an int value in the default radix using the nextInt() method. 14 boolean hasNextLine() This method returns true if there is another line in the input of this scanner. 15 boolean hasNextLong() This method returns true if the next token in this scanner”s input can be interpreted as a long value in the default radix using the nextLong() method. 16 boolean hasNextShort() This method returns true if the next token in this scanner”s input can be interpreted as a short value in the default radix using the nextShort() method. 17 IOException ioException() This method returns the IOException last thrown by this Scanner”s underlying Readable. 18 Locale locale() This method returns this scanner”s locale. 19 MatchResult match() This method returns the match result of the last scanning operation performed by this scanner. 20 String next() This method finds and returns the next complete token from this scanner. 21 BigDecimal nextBigDecimal() This method scans the next token of the input as a BigDecimal. 22 BigInteger nextBigInteger() This method Scans the next token of the input as a BigInteger. 23 boolean nextBoolean() This method scans the next token of the input into a boolean value and returns that value. 24 byte nextByte() This method scans the next token of the input as a byte. 25 double nextDouble() This method scans the next token of the input as a double. 26 float nextFloat() This method scans the next token of the input as a float. 27 int nextInt() This method scans the next token of the input as an int. 28 String nextLine() This method advances this scanner past the current line and returns the input that was skipped. 29 long nextLong() This method scans the next token of the input as a long. 30 short nextShort() This method scans the next token of the input as a short. 31 int radix() This method returns this scanner”s default radix. 32 void remove() The remove operation is not supported by this implementation of Iterator. 33 Scanner reset() This method resets this scanner. 34 Scanner skip(Pattern pattern) This method skips input that matches the specified pattern, ignoring delimiters. 35 Stream<String> tokens() Returns a stream of delimiter-separated tokens from this scanner. 36 String toString() This method returns the string representation of
Java – ArrayDeque
Java ArrayDeque Class ”; Previous Next Introduction The Java ArrayDeque class provides resizable-array and implements the Deque interface. Following are the important points about Array Deques − Array deques have no capacity restrictions so they grow as necessary to support usage. They are not thread-safe; in the absence of external synchronization. They do not support concurrent access by multiple threads. Null elements are prohibited in the array deques. They are faster than Stack and LinkedList. This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces. ArrayDeque Class Declaration Following is the declaration for java.util.ArrayDeque class − public class ArrayDeque<E> extends AbstractCollection<E> implements Serializable, Cloneable, Iterable<E>, Collection<E>, Deque<E>, Queue<E> Here <E> represents an Element, which could be any class. For example, if you”re building an array deque of Integers then you”d initialize it as − Deque<Integer> objDeque = new ArrayDeque<>(); ArrayDeque Class Constructors Sr.No. Constructor & Description 1 ArrayDeque() This constructor is used to create an empty array deque with an initial capacity sufficient to hold 16 elements. 2 ArrayDeque(Collection<? extends E> c) This constructor is used to create a deque containing the elements of the specified collection. 3 ArrayDeque(int numElements) This constructor is used to create an empty array deque with an initial capacity sufficient to hold the specified number of elements. ArrayDeque Class Methods Sr.No. Method & Description 1 boolean add(E e) This method inserts the specified element at the end of this deque. 2 boolean addAll(Collection<? extends E> c) This method adds all of the elements in the specified collection at the end of this deque, as if by calling addLast(E) on each one, in the order that they are returned by the collection”s iterator. 3 void addFirst(E e) This method inserts the specified element at the front of this deque. 4 void addLast(E e) This method inserts the specified element at the end of this deque. 5 void clear() This method removes all of the elements from this deque. 6 ArrayDeque<E> clone() This method returns a copy of this deque. 7 boolean contains(Object o) This method returns true if this deque contains the specified element. 8 E element() This method retrieves, but does not remove, the head of the queue represented by this deque. 9 void forEach(Consumer<? super E> action) This method performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. 10 E getFirst() This method retrieves, but does not remove, the first element of this deque. 11 E getLast() This method retrieves, but does not remove, the last element of this deque. 12 boolean isEmpty() This method returns true if this deque contains no elements. 13 Iterator<E> iterator() This method returns an iterator over the elements in this deque. 14 boolean offer(E e) This method inserts the specified element at the end of this deque. 15 boolean offerFirst(E e) This method inserts the specified element at the front of this deque. 16 boolean offerLast(E e) This method inserts the specified element at the end of this deque. 17 E peek() This method retrieves, but does not remove, the head of the queue represented by this deque, or returns null if this deque is empty. 18 E poll() This method retrieves and removes the head of the queue represented by this deque, or returns null if this deque is empty. 19 E pollFirst() This method retrieves and removes the first element of this deque, or returns null if this deque is empty. 20 E pollLast() This method retrieves and removes the last element of this deque, or returns null if this deque is empty. 21 E pop() This method pops an element from the stack represented by this deque. 22 void push(E e) This method pushes an element onto the stack represented by this deque. 23 E remove() This method retrieves and removes the head of the queue represented by this deque. 24 boolean removeAll(Collection<?> c) This method removes all of this collection”s elements that are also contained in the specified collection. 25 E removeFirst() This method retrieves and removes the first element of this deque. 26 boolean removeFirstOccurrence(Object o) This method removes the first occurrence of the specified element in this deque. 27 boolean removeIf(Predicate<? super E> filter) This method removes all of the elements of this collection that satisfy the given predicate. 28 E removeLast() This method retrieves and removes the last element of this deque. 29 boolean removeLastOccurrence(Object o) This method removes the last occurrence of the specified element in this deque. 30 boolean retainAll(Collection<?> c) This method retains only the elements in this collection that are contained in the specified collection (optional operation). 31 int size() This method returns the number of elements in this deque. 32 Spliterator<E> spliterator() This method creates a late-binding and fail-fast Spliterator over the elements in this deque. 33 object[] toArray() This method returns an array containing all of the elements in this deque in proper sequence. Adding and Removing Elements from an ArrayDeque Example This Java example demonstrates how you can use an ArrayDeque Class. // Importing classes import java.util.ArrayDeque; import java.util.Deque; // Public Main Class public class Main { public static void main(String[] args) { // The main() function Deque < Integer > objDeque = new ArrayDeque < > (); // Adding elements at first and last objDeque.addFirst(15); objDeque.addLast(28); // Removing the elements int ele1 = objDeque.removeFirst(); int ele2 = objDeque.removeLast(); // Printing removed elements System.out.println(“First removed element is : ” + ele1); System.out.println(“Last removed element is : ” + ele2); } } Output This will produce the following result − First removed element is : 15 Last removed element is : 28 Print Page Previous Next Advertisements ”;
Java – Teeing Collectors
Java – Teeing Collectors ”; Previous Next Java Collectors.teeing() Method Java 12 introduced a new static method to Collectors interface which can perform two different operations on collection and then merge the result. Syntax Following is the syntax of teeing method − public static Collector<T, ?, R> teeing( Collector<? super T, ?, R1> downstream1, Collector<? super T, ?, R2> downstream2, BiFunction<? super R1, ? super R2, R> merger ) Here each element of the collection passed to the teeing collector is processed by downstream1 and downstream2 collectors, once the processing is completed by both the collectors, the results are passed to the BiFunction collector to merge the result or process accordingly. It is similar to calling two functions on a collection and then calling the third function to process the results of first two functions. Here we are performing different functions on a collection and then merge the result using merger BiFunction. Example – Using teeing collectors to get mean of n numbers In this example, we”re getting sum of numbers in downstream1 collector, count of numbers in downstream2 collector and then computing mean in the merger function. This is useful when we”re getting a stream of numbers and size of stream is not available. package com.tutorialspoint; import java.util.stream.Collectors; import java.util.stream.Stream; public class Tester { public static void main(String[] args) { double mean = Stream.of(1, 2, 3, 4, 5, 6, 7) .collect(Collectors.teeing( Collectors.summingDouble(i -> i), Collectors.counting(), (sum, n) -> sum / n)); System.out.println(mean); } } Output Let us compile and run the above program, this will produce the following result − 4.0 Example – Using teeing collectors to get lowest and highest marks of student objects In this example, we”re getting lowest marks of students in downstream1 collector and highest marks of students in downstream2 collector. Then using merger function, we”re creating a hashmap with entry of student having lowest and highest marks. package com.tutorialspoint; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.stream.Collectors; public class Tester { public static void main(String args[]) { // list of students List<Student> students = Arrays.asList( new Student(1, “Robert”, 390), new Student(2, “Julie”, 410), new Student(3, “John”, 440), new Student(4, “Michael”, 420)); // collect the result in hashmap HashMap<String, Student> result = students.stream().collect( // apply the teeing operator Collectors.teeing( // get the student having highest marks Collectors.maxBy(Comparator.comparing(Student::getMarks)), // get the student having lowest marks Collectors.minBy(Comparator.comparing(Student::getMarks)), // put both student entries in the map using merger (s1, s2) -> { HashMap<String, Student> map = new HashMap<>(); map.put(“Highest”, s1.get()); map.put(“Lowest”, s2.get()); return map; } )); System.out.println(result); } } class Student { int rollNo; String name; int marks; public Student(int rollNo, String name, int marks) { this.rollNo = rollNo; this.name = name; this.marks = marks; } @Override public String toString() { return “Student [RollNo=” + rollNo + “, Name=” + name + “, Marks=” + marks + “]”; } public int getRollNo() { return rollNo; } public void setRollNo(int rollNo) { this.rollNo = rollNo; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getMarks() { return marks; } public void setMarks(int marks) { this.marks = marks; } } Output Let us compile and run the above program, this will produce the following result − {Lowest=Student [RollNo=1, Name=Robert, Marks=390], Highest=Student [RollNo=3, Name=John, Marks=440]} Print Page Previous Next Advertisements ”;
Java – TreeMap
Java TreeMap Class ”; Previous Next Introduction The Java TreeMap class is the Red-Black tree based implementation of the Map interface.Following are the important points about TreeMap − The TreeMap class guarantees that the Map will be in ascending key order. The Map is sorted according to the natural sort method for the key Class, or by the Comparator provided at map creation time, that will depend on which constructor used. Class declaration Following is the declaration for java.util.TreeMap class − public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>, Cloneable, Serializable Parameters Following is the parameter for java.util.TreeMap class − K − This is the type of keys maintained by this map. V − This is the type of mapped values. Class constructors Sr.No. Constructor & Description 1 TreeMap() This constructor constructs a new, empty tree map, using the natural ordering of its keys. 2 TreeMap(Comparator<? super K> comparator) This constructor constructs a new, empty tree map, ordered according to the given comparator. 3 TreeMap(Map<? extends K,? extends V> m) This constructor constructs a new tree map containing the same mappings as the given map, ordered according to the natural ordering of its keys. 4 TreeMap(SortedMap<K,? extends V> m) This constructor constructs a new tree map containing the same mappings and using the same ordering as the specified sorted map. Class methods Sr.No. Method & Description 1 Map.Entry<K,V> ceilingEntry(K key) This method returns a key-value mapping associated with the least key greater than or equal to the given key, or null if there is no such key. 2 K ceilingKey(K key) This method returns the least key greater than or equal to the given key, or null if there is no such key. 3 void clear() This method removes all of the mappings from this map. 4 Object clone() This method returns a shallow copy of this TreeMap instance. 5 boolean containsKey(Object key) This method returns true if this map contains a mapping for the specified key. 6 boolean containsValue(Object value) This method returns true if this map maps one or more keys to the specified value. 7 NavigableSet<K> descendingKeySet() This method returns a reverse order NavigableSet view of the keys contained in this map. 8 NavigableMap<K,V> descendingMap() This method returns a reverse order view of the mappings contained in this map. 9 Set<Map.Entry<K,V>> entrySet() This method returns a Set view of the mappings contained in this map. 10 Map.Entry<K,V> firstEntry() This method returns a key-value mapping associated with the least key in this map, or null if the map is empty. 11 K firstKey() This method returns the first (lowest) key currently in this map. 12 Map.Entry<K,V> floorEntry(K key) This method returns a key-value mapping associated with the greatest key less than or equal to the given key, or null if there is no such key. 13 K floorKey(K key) This method returns the greatest key less than or equal to the given key, or null if there is no such key. 14 V get(Object key) This method returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. 15 SortedMap<K,V> headMap(K toKey) This method returns a view of the portion of this map whose keys are strictly less than toKey. 16 Map.Entry<K,V> higherEntry(K key) This method returns the returns a key-value mapping associated with the least key strictly greater than the given key, or null if there is no such key. 17 K higherKey(K key) This method returns the least key strictly greater than the given key, or null if there is no such key. 18 Set<K> keySet() This method returns a Set view of the keys contained in this map. 19 Map.Entry<K,V> lastEntry() This method returns a key-value mapping associated with the greatest key in this map, or null if the map is empty. 20 K lastKey() This method returns the last (highest) key currently in this map. 21 Map.Entry<K,V> lowerEntry(K key) This method returns a key-value mapping associated with the greatest key strictly less than the given key, or null if there is no such key. 22 K lowerKey(K key) This method returns the greatest key strictly less than the given key, or null if there is no such key. 23 NavigableSet<K> navigableKeySet() This method returns a NavigableSet view of the keys contained in this map. 24 Map.Entry<K,V> pollFirstEntry() This method removes and returns a key-value mapping associated with the least key in this map, or null if the map is empty. 25 Map.Entry<K,V> pollLastEntry() This method removes and returns a key-value mapping associated with the greatest key in this map, or null if the map is empty. 26 V put(K key, V value) This method associates the specified value with the specified key in this map. 27 void putAll(Map<? extends K,? extends V> map) This method copies all of the mappings from the specified map to this map. 28 V remove(Object key) This method removes the mapping for this key from this TreeMap if present. 29 int size() This method returns the number of key-value mappings in this map. 30 SortedMap<K,V> subMap(K fromKey, K toKey) This method returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive 31 SortedMap<K,V> tailMap(K fromKey) This method returns a view of the portion of this map whose keys are greater than or equal to fromKey. 32 Collection<V> values() This method returns a Collection view of the values contained in this map. Methods inherited This class inherits methods from the following classes − java.util.AbstractMap java.util.Object java.util.Map Adding and Getting a Value from a TreeMap Example The following example shows the usage of Java TreeMap get() method to get the value associated with the given key in the map. We”ve created a TreeMap object of Integer,Integer. Then few entries are added, and using get() we”re printing a value for a given key. package com.tutorialspoint; import java.util.TreeMap; public class TreeMapDemo { public static void main(String[] args) { // creating tree map
Java – Date
Java Date Class ”; Previous Next Introduction The Java Util Date class represents a specific instant in time, with millisecond precision. Class declaration Following is the declaration for java.util.Date class − public class Date extends Object implements Serializable, Cloneable, Comparable<Date> Class constructors Sr.No. Constructor & Description 1 Date() This constructor allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond. 2 Date(long date) This constructor allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as “the epoch”, namely January 1, 1970, 00:00:00 GMT. Class methods Sr.No. Method & Description 1 boolean after(Date when) This method tests if this date is after the specified date. 2 boolean before(Date when) This method tests if this date is before the specified date. 3 Object clone() This method return a copy of this object. 4 int compareTo(Date anotherDate) This method compares two Dates for ordering. 5 boolean equals(Object obj) This method compares two dates for equality. 6 static Date from(Instant instant) This method obtains an instance of Date from an Instant object. 7 long getTime() This method returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object. 8 int hashCode() This method returns a hash code value for this object. 9 void setTime(long time) This method sets this Date object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT. 10 Instant toInstant() This method converts this Date object to an Instant. 11 String toString() This method converts this Date object to a String of the form. Methods inherited This class inherits methods from the following classes − java.util.Object Creating a Date instance of current date Example This Java example demonstrates the from() method of Date class to get Date instance of current time. package com.tutorialspoint; import java.time.Instant; // Import the Date package import java.util.Date; // Main public class public class DateDemo { public static void main(String[] args) { // create a date of current time Date date = Date.from(Instant.now()); // print the date instance System.out.println(“Date: ” + date.toString()); } } Output Let us compile and run the above program, this will produce the following result − Date: Mon Apr 01 10:20:08 IST 2024 Print Page Previous Next Advertisements ”;