Java – HashSet

Java HashSet Class ”; Previous Next Introduction The Java HashSet class implements the Set interface, backed by a hash table.Following are the important points about HashSet − This class makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element. Class declaration Following is the declaration for java.util.HashSet class − public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable Parameters Following is the parameter for java.util.HashSet class − E − This is the type of elements maintained by this set. Class constructors Sr.No. Constructor & Description 1 HashSet() This constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor (0.75). 2 HashSet(Collection<? extends E> c) This constructs a new set containing the elements in the specified collection. 3 HashSet(int initialCapacity) This constructs a new, empty set; the backing HashMap instance has the specified initial capacity and default load factor (0.75). 4 HashSet(int initialCapacity, float loadFactor) This constructs a new, empty set; the backing HashMap instance has the specified initial capacity and the specified load factor. 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 void clear() This method removes all of the elements from this set. 3 Object clone() This method returns a shallow copy of this HashSet instance, the elements themselves are not cloned. 4 boolean contains(Object o) This method returns true if this set contains the specified element. 5 boolean isEmpty() This method returns true if this set contains no elements. 6 Iterator<E> iterator() This method returns an iterator over the elements in this set. 7 boolean remove(Object o) This method removes the specified element from this set if it is present. 8 int size() This method returns returns the number of elements in this set(its cardinality). 9 Spliterator<E> spliterator() This method returns a late-binding and fail-fast Spliterator over the elements in this set. Methods inherited This class inherits methods from the following classes − java.util.AbstractSet java.util.AbstractCollection java.util.Object java.util.Set Adding element to a HashSet Example The following example shows the usage of Java HashSet add() method to add entries to the HashSet. We”ve created a HashSet object of Integer. Then few entries are added using add() method and then set is printed. package com.tutorialspoint; import java.util.HashSet; public class HashSetDemo { public static void main(String args[]) { // create hash set HashSet <Integer> newset = new HashSet <>(); // populate hash set newset.add(1); newset.add(2); newset.add(3); // checking elements in hash set System.out.println(“Hash set values: “+ newset); } } Output Let us compile and run the above program, this will produce the following result. Hash set values: [1, 2, 3] Print Page Previous Next Advertisements ”;

Java – Questions and Answers

JAVA Questions and Answers ”; Previous Next JAVA Questions and Answers has been designed with a special intention of helping students and professionals preparing for various Certification Exams and Job Interviews. This section provides a useful collection of sample Interview Questions and Multiple Choice Questions (MCQs) and their answers with appropriate explanations. SN Question/Answers Type 1 JAVA Interview Questions This section provides a huge collection of JAVA Interview Questions with their answers hidden in a box to challenge you to have a go at them before discovering the correct answer. 2 JAVA Online Quiz This section provides a great collection of JAVA Multiple Choice Questions (MCQs) on a single page along with their correct answers and explanation. If you select the right option, it turns green; else red. 3 JAVA Online Test If you are preparing to appear for a Java and JAVA related certification exam, then this section is a must for you. This section simulates a real online test along with a given timer which challenges you to complete the test within a given time-frame. Finally you can check your overall test score and how you fared among millions of other candidates who attended this online test. 4 JAVA Mock Test This section provides various mock tests that you can download at your local machine and solve offline. Every mock test is supplied with a mock test key to let you verify the final score and grade yourself. Print Page Previous Next Advertisements ”;

Java – HashMap

Java HashMap Class ”; Previous Next Introduction The Java HashMap class is the Hash table based implementation of the Map interface.Following are the important points about HashMap − This class makes no guarantees as to the iteration order of the map; in particular, it does not guarantee that the order will remain constant over time. This class permits null values and the null key. Class declaration Following is the declaration for java.util.HashMap class − public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable Parameters Following is the parameter for java.util.HashMap 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 HashMap() This constructs an empty HashMap with the default initial capacity (16) and the default load factor (0.75). 2 HashMap(int initialCapacity) This constructs an empty HashMap with the specified initial capacity and the default load factor (0.75). 3 HashMap(int initialCapacity, float loadFactor) This constructs an empty HashMap with the specified initial capacity and load factor. 4 HashMap(Map<? extends K,? extends V> m) This constructs a new HashMap with the same mappings as 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 HashMap instance, the keys and values themselves are not cloned. 3 V compute​(K key, BiFunction<? super K,​? super V,​? extends V> remappingFunction) Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping). 4 V computeIfAbsent​(K key, Function<? super K,​? extends V> mappingFunction) If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null. 5 V computeIfPresent​(K key, BiFunction<? super K,​? super V,​? extends V> remappingFunction) If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value. 6 boolean containsKey(Object key) This method returns true if this map contains a mapping for the specified key. 7 boolean containsValue(Object value) This method returns true if this map maps one or more keys to the specified value. 8 Set<Map.Entry<K,V>> entrySet() This method returns a Set view of the mappings contained in this map. 9 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. 10 boolean isEmpty() This method returns true if this map contains no key-value mapping. 11 Set<K> keySet() This method returns a Set view of the keys contained in this map. 12 V merge​(K key, V value, BiFunction<? super V,​? super V,​? extends V> remappingFunction) If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. 13 V put(K key, V value) This method associates the specified value with the specified key in this map. 14 void putAll(Map<? extends K,? extends V> m) This method copies all of the mappings from the specified map to this map. 15 V remove(Object key) This method removes the mapping for the specified key from this map if present. 16 int size() This method returns the number of key-value mappings in this map. 17 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 Example The following program illustrates several of the methods supported by HashMap collection − import java.util.*; public class HashMapDemo { public static void main(String args[]) { // Create a hash map HashMap hm = new HashMap(); // Put elements to the map hm.put(“Zara”, new Double(3434.34)); hm.put(“Mahnaz”, new Double(123.22)); hm.put(“Ayan”, new Double(1378.00)); hm.put(“Daisy”, new Double(99.22)); hm.put(“Qadir”, new Double(-19.08)); // Get a set of the entries Set set = hm.entrySet(); // Get an iterator Iterator i = set.iterator(); // Display elements while(i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); System.out.print(me.getKey() + “: “); System.out.println(me.getValue()); } System.out.println(); // Deposit 1000 into Zara”s account double balance = ((Double)hm.get(“Zara”)).doubleValue(); hm.put(“Zara”, new Double(balance + 1000)); System.out.println(“Zara”s new balance: ” + hm.get(“Zara”)); } } This will produce the following result − Output Daisy: 99.22 Ayan: 1378.0 Zara: 3434.34 Qadir: -19.08 Mahnaz: 123.22 Zara”s new balance: 4434.34 Print Page Previous Next Advertisements ”;

Java – Switch

Java – switch statement ”; Previous Next Java switch Statement The Java switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case. The switch statement can be used when multiple if-else statements are required. It can have multiple code blocks along with the case values and executes one of many code blocks based on the matches case value. Syntax The syntax of Java switch statement is − switch(expression) { case value : // Statements break; // optional case value : // Statements break; // optional // You can have any number of case statements. default : // Optional // Statements } Rules The following rules apply to a switch statement − The variable used in a switch statement can only be integers, convertable integers (byte, short, char), strings and enums. You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon. The value for a case must be the same data type as the variable in the switch and it must be a constant or a literal. When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached. When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement. Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached. A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case. Flow Diagram Examples Example 1 In this example, we”re showing use of switch statement where cases are based on a char. We”ve created a variable grade. Based on value of grade, each case is checked. if a case is satisfied and break statement is present then following cases are not checked. public class Test { public static void main(String args[]) { char grade = ”C”; switch(grade) { case ”A” : System.out.println(“Excellent!”); break; case ”B” : case ”C” : System.out.println(“Well done”); break; case ”D” : System.out.println(“You passed”); case ”F” : System.out.println(“Better try again”); break; default : System.out.println(“Invalid grade”); } System.out.println(“Your grade is ” + grade); } } Output Compile and run the above program using various command line arguments. This will produce the following result − Well done Your grade is C Example 2 In this example, we”re showing use of switch statement where cases are based on a int. We”ve created a variable grade. Based on value of grade, each case is checked. if a case is satisfied and break statement is present then following cases are not checked. public class Test { public static void main(String args[]) { int grade = 3; switch(grade) { case 1 : System.out.println(“Excellent!”); break; case 2 : case 3 : System.out.println(“Well done”); break; case 4 : System.out.println(“You passed”); case 5 : System.out.println(“Better try again”); break; default : System.out.println(“Invalid grade”); } System.out.println(“Your grade is ” + grade); } } Output Compile and run the above program using various command line arguments. This will produce the following result − Well done Your grade is 3 Example 3 In this example, we”re showing use of switch statement where cases are based on a String. We”ve created a variable grade. Based on value of grade, each case is checked. if a case is satisfied and break statement is present then following cases are not checked. public class Test { public static void main(String args[]) { String grade = “C”; switch(grade) { case “A” : System.out.println(“Excellent!”); break; case “B” : case “C” : System.out.println(“Well done”); break; case “D” : System.out.println(“You passed”); case “F” : System.out.println(“Better try again”); break; default : System.out.println(“Invalid grade”); } System.out.println(“Your grade is ” + grade); } } Output Compile and run the above program using various command line arguments. This will produce the following result − Well done Your grade is C The default Keyword The default keyword is used to specify a code block when no case value is matched. The default keyword is optional, but it should be used in the switch case statement. java_decision_making.htm Print Page Previous Next Advertisements ”;

Java Vs. C++

Java vs C++ ”; Previous Next Java is a general-purpose, high-level programming language. Java is used for web development, Machine Learning, and other cutting-edge software development. Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and released in 1995 as core component of Sun Microsystems” Java platform (Java 1.0 [J2SE]) C++ is a middle-level, case-sensitive, object-oriented programming language. Bjarne Stroustrup created C++ at Bell Labs. C++ is a platform-independent programming language that works on Windows, Mac OS, and Linux. C++ is near to hardware, allowing low-level programming. This provides a developer control over memory, improved performance, and dependable software. Read through this article to get an overview of C++ and Java and how these two programming languages are different from each other. What is Java? The latest release of the Java Standard Edition is Java SE 21. With the advancement of Java and its widespread popularity, multiple configurations were built to suit various types of platforms. For example: J2EE for Enterprise Applications, J2ME for Mobile Applications. The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively. Java is guaranteed to be Write Once, Run Anywhere. Features of Java Java is − Object Oriented − In Java, everything is an Object. Java can be easily extended since it is based on the Object model. Platform Independent − Unlike many other programming languages including C and C&plus;&plus;, when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by the Java Virtual Machine (JVM) on whichever platform it is being run on. Simple − Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it would be easy to master. Secure − With Java”s secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques are based on public-key encryption. Architecture-neutral − Java compiler generates an architecture-neutral object file format, which makes the compiled code executable on many processors, with the presence of Java runtime system. Portable − Being architecture-neutral and having no implementation dependent aspects of the specification makes Java portable. Compiler in Java is written in ANSI C with a clean portability boundary, which is a POSIX subset. Robust − Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and runtime checking. Multithreaded − With Java”s multithreaded feature it is possible to write programs that can perform many tasks simultaneously. This design feature allows the developers to construct interactive applications that can run smoothly. Interpreted − Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light-weight process. High Performance − With the use of Just-In-Time compilers, Java enables high performance. Distributed − Java is designed for the distributed environment of the internet. Dynamic − Java is considered to be more dynamic than C or C&plus;&plus; since it is designed to adapt to an evolving environment. Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time. Java Example Take a look at the following simple Java program − package com.tutorialspoint; import java.util.Scanner; public class JavaTester { public static void main(String args[]) { String a, b; Scanner scanner = new Scanner(System.in); System.out.println(“Enter The value for variable a”); a = scanner.nextLine(); System.out.println(“Enter The value for variable b”); b = scanner.nextLine(); System.out.println(“The value you have entered for a is ” + a); System.out.println(“The value you have entered for b is ” + b); scanner.close(); } } In our example, we have taken two variables “a” and “b” and assigning some value to those variables. Note that in Java, we need to declare datatype for variables explicitly, as Java is strictly typed language. As Java is an object oriented language, we uses objects to perform any action. In the example, we”ve used Scanner class object to read user input from console which is represented by System.in object. System.out object method println() is used to print the values received. Output On execution, this Java code will produce the following output − Enter The value for variable a 10 Enter The value for variable b 20 The value you have entered for a is 10 The value you have entered for b is 20 What is C++? C++ is a statically typed, compiled, multi-paradigm, general-purpose programming language with a steep learning curve. Video games, desktop apps, and embedded systems use it extensively. C++ is so compatible with C that it can build practically all C source code without any changes. Object-oriented programming makes C++ a better-structured and safer language than C. Features of C++ Let”s see some features of C++ and the reason of its popularity. Middle-level language − It”s a middle-level language since it can be used for both systems development and large-scale consumer applications like Media Players, Photoshop, Game Engines, etc. Execution Speed − C++ code runs quickly. Because it”s compiled and uses procedures extensively. Garbage collection, dynamic typing, and other modern features impede program execution. Object-oriented language − Object-oriented programming is flexible and manageable. Large apps are possible. Growing code makes procedural code harder to handle. C++”s key advantage over C. Extensive Library Support − C++ has a vast library. Third-party libraries are supported for fast development. C++ Example Let”s understand the syntax of C++ through an example written below. #include using namespace std; int main() { int a, b; cout << “Enter The value for variable a n”; cin >> a; cout << “Enter The value for variable b”; cin >> b; cout << “The value of a is “<< a << “and” << b; return 0; } In our example, we are taking input for two variables “a” and “b” from the user through the keyboard and displaying the data

Java – BitSet

Java BitSet Class ”; Previous Next Introduction The Java BitSet class creates a special type of array that holds bit values. The BitSet array can increase in size as needed. This makes it similar to a vector of bits. This is a legacy class but it has been completely re-engineered in Java 2, version 1.4. The Java BitSet class implements a vector of bits that grows as needed.Following are the important points about BitSet − A BitSet is not safe for multithreaded use without external synchronization. All bits in the set initially have the value false. Passing a null parameter to any of the methods in a BitSet will result in a NullPointerException. Class declaration Following is the declaration for java.util.BitSet class − public class BitSet extends Object implements Cloneable, Serializable Class constructors Sr.No. Constructor & Description 1 BitSet() This constructor creates a new bit set. 2 BitSet(int nbits) This constructor creates a bit set whose initial size is large enough to explicitly represent bits with indices in the range 0 through nbits-1. Class methods Sr.No. Method & Description 1 void and(BitSet set) This method performs a logical AND of this target bit set with the argument bit set. 2 void andNot(BitSet set) This method clears all of the bits in this BitSet whose corresponding bit is set in the specified BitSet. 3 int cardinality() This method returns the number of bits set to true in this BitSet. 4 void clear() This method sets all of the bits in this BitSet to false. 5 Object clone() This method clones this BitSet and produces a new BitSet that is equal to it. 6 boolean equals(Object obj) This method compares this object against the specified object. 7 void flip(int bitIndex) This method sets the bit at the specified index to the complement of its current value. 8 boolean get(int bitIndex) This method returns the value of the bit with the specified index. 9 int hashCode() This method returns the value of the bit with the specified index. 10 boolean intersects(BitSet set) This method returns true if the specified BitSet has any bits set to true that are also set to true in this BitSet. 11 boolean isEmpty() This method returns true if this BitSet contains no bits that are set to true. 12 int length() This method returns the “logical size” of this BitSet: the index of the highest set bit in the BitSet plus one. 13 int nextClearBit(int fromIndex) This method returns the index of the first bit that is set to false that occurs on or after the specified starting index. 14 int nextSetBit(int fromIndex) This method returns the index of the first bit that is set to true that occurs on or after the specified starting index. 15 void or(BitSet set) This method performs a logical OR of this bit set with the bit set argument. 16 int previousClearBit(int fromIndex) This method returns the index of the first bit that is set to false that occurs on or before the specified starting index. 17 int previousSetBit(int fromIndex) This method returns the index of the first bit that is set to true that occurs on or after the specified starting index. 18 void set(int bitIndex) This method sets the bit at the specified index to true. 19 int size() This method returns the number of bits of space actually in use by this BitSet to represent bit values. 20 IntStream stream() This method returns a stream of indices for which this BitSet contains a bit in the set state. 21 byte[] toByteArray() This method returns a new bit set containing all the bits in the given byte array. 22 long[] toLongArray() This method returns a new long array containing all the bits in this bit set. 23 String toString() This method returns a string representation of this bit set. 24 static BitSet valueOf​(byte[] bytes) This method returns a new bit set containing all the bits in the given byte array. 25 void xor(BitSet set) This method performs a logical XOR of this bit set with the bit set argument. Methods inherited This class inherits methods from the following classes − java.util.Object Creating a BitSet and Performing Operations on BitSets Example The following program illustrates several of the methods supported by BitSet data structure − import java.util.BitSet; public class BitSetDemo { public static void main(String args[]) { BitSet bits1 = new BitSet(16); BitSet bits2 = new BitSet(16); // set some bits for(int i = 0; i < 16; i++) { if((i % 2) == 0) bits1.set(i); if((i % 5) != 0) bits2.set(i); } System.out.println(“Initial pattern in bits1: “); System.out.println(bits1); System.out.println(“nInitial pattern in bits2: “); System.out.println(bits2); // AND bits bits2.and(bits1); System.out.println(“nbits2 AND bits1: “); System.out.println(bits2); // OR bits bits2.or(bits1); System.out.println(“nbits2 OR bits1: “); System.out.println(bits2); // XOR bits bits2.xor(bits1); System.out.println(“nbits2 XOR bits1: “); System.out.println(bits2); } } This will produce the following result − Output Initial pattern in bits1: {0, 2, 4, 6, 8, 10, 12, 14} Initial pattern in bits2: {1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14} bits2 AND bits1: {2, 4, 6, 8, 12, 14} bits2 OR bits1: {0, 2, 4, 6, 8, 10, 12, 14} bits2 XOR bits1: {} Print Page Previous Next Advertisements ”;

Java – Quick Guide

Java – Quick Guide ”; Previous Next Java – Overview Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and released in 1995 as core component of Sun Microsystems” Java platform (Java 1.0 [J2SE]). The latest release of the Java Standard Edition is Java SE 8. With the advancement of Java and its widespread popularity, multiple configurations were built to suit various types of platforms. For example: J2EE for Enterprise Applications, J2ME for Mobile Applications. The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively. Java is guaranteed to be Write Once, Run Anywhere. Java is − Object Oriented − In Java, everything is an Object. Java can be easily extended since it is based on the Object model. Platform Independent − Unlike many other programming languages including C and C&plus;&plus;, when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by the Virtual Machine (JVM) on whichever platform it is being run on. Simple − Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it would be easy to master. Secure − With Java”s secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques are based on public-key encryption. Architecture-neutral − Java compiler generates an architecture-neutral object file format, which makes the compiled code executable on many processors, with the presence of Java runtime system. Portable − Being architecture-neutral and having no implementation dependent aspects of the specification makes Java portable. Compiler in Java is written in ANSI C with a clean portability boundary, which is a POSIX subset. Robust − Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and runtime checking. Multithreaded − With Java”s multithreaded feature it is possible to write programs that can perform many tasks simultaneously. This design feature allows the developers to construct interactive applications that can run smoothly. Interpreted − Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light-weight process. High Performance − With the use of Just-In-Time compilers, Java enables high performance. Distributed − Java is designed for the distributed environment of the internet. Dynamic − Java is considered to be more dynamic than C or C&plus;&plus; since it is designed to adapt to an evolving environment. Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time. Hello World using Java Programming. Just to give you a little excitement about Java programming, I”m going to give you a small conventional C Programming Hello World program, You can try it using Demo link. public class MyFirstJavaProgram { /* This is my first java program. * This will print ”Hello World” as the output */ public static void main(String []args) { System.out.println(“Hello World”); // prints Hello World } } History of Java James Gosling initiated Java language project in June 1991 for use in one of his many set-top box projects. The language, initially called ”Oak” after an oak tree that stood outside Gosling”s office, also went by the name ”Green” and ended up later being renamed as Java, from a list of random words. Sun released the first public implementation as Java 1.0 in 1995. It promised Write Once, Run Anywhere (WORA), providing no-cost run-times on popular platforms. On 13 November, 2006, Sun released much of Java as free and open source software under the terms of the GNU General Public License (GPL). On 8 May, 2007, Sun finished the process, making all of Java”s core code free and open-source, aside from a small portion of code to which Sun did not hold the copyright. Tools You Will Need For performing the examples discussed in this tutorial, you will need a Pentium 200-MHz computer with a minimum of 64 MB of RAM (128 MB of RAM recommended). You will also need the following softwares − Linux 7.1 or Windows xp/7/8 operating system Java JDK 8 Microsoft Notepad or any other text editor This tutorial will provide the necessary skills to create GUI, networking, and web applications using Java. What is Next? The next chapter will guide you to how you can obtain Java and its documentation. Finally, it instructs you on how to install Java and prepare an environment to develop Java applications. Java – Environment Setup Live Demo Option Online We have set up the Java Programming environment online, so that you can compile and execute all the available examples online. It gives you confidence in what you are reading and enables you to verify the programs with different options. Feel free to modify any example and execute it online. Try the following example using Live Demo option available at the top right corner of the below sample code box − public class MyFirstJavaProgram { public static void main(String []args) { System.out.println(“Hello World”); } } For most of the examples given in this tutorial, you will find a Try it option in our website code sections at the top right corner that will take you to the online compiler. So just make use of it and enjoy your learning. Local Environment Setup If you want to set up your own environment for Java programming language, then this section guides you through the whole process. Please follow the steps given below to set up your Java environment. Java SE is available for download

Java – Dictionary

Java Dictionary Class ”; Previous Next Introduction The Java Dictionary class is the abstract parent of any class, such as Hashtable, which maps keys to values.Following are the important points about Dictionary − In this class every key and every value is an object. In his class object every key is associated with at most one value. Class declaration Following is the declaration for java.util.Dictionary class − public abstract class Dictionary<K,V> extends Object Class constructors Sr.No. Constructor & Description 1 Dictionary() This is the single constructor. Class methods Sr.No. Method & Description 1 abstract Enumeration<V> elements() This method returns an enumeration of the values in this dictionary. 2 abstract V get(Object key) This method returns the value to which the key is mapped in this dictionary. 3 abstract boolean isEmpty() This method tests if this dictionary maps no keys to value. 4 abstract Enumeration<K> keys() This method returns an enumeration of the keys in this dictionary. 5 abstract V put(K key, V value) This method maps the specified key to the specified value in this dictionary. 6 abstract V remove(Object key) This method removes the key (and its corresponding value) from this dictionary. 7 abstract int size() This method returns the number of entries (distinct keys) in this dictionary. Methods inherited This class inherits methods from the following classes − java.util.Object Adding a Mapping to Dictionary of Integer, Integer Example The following example shows the usage of Java Dictionary put(K,V) method. We”re creating a dictionary instance using Hashtable object of Integer, Integer. Then we”ve added few elements to it using put(K,V) method. An enumeration is retrieved using elements() method and enumeration is then iterated to print the elements of the dictionary. package com.tutorialspoint; import java.util.Enumeration; import java.util.Dictionary; import java.util.Hashtable; public class DictionaryDemo { public static void main(String[] args) { // create a new hashtable Dictionary<Integer, Integer> dictionary = new Hashtable<>(); // add 2 elements dictionary.put(1, 1); dictionary.put(2, 2); Enumeration<Integer> enumeration = dictionary.elements(); while(enumeration.hasMoreElements()) { System.out.println(enumeration.nextElement()); } } } Let us compile and run the above program, this will produce the following result − 2 1 Print Page Previous Next Advertisements ”;

Java – Streams

Java – Streams ”; Previous Next Stream is a new abstract layer introduced in Java 8. Using stream, you can process data in a declarative way similar to SQL statements. For example, consider the following SQL statement. SELECT max(salary), employee_id, employee_name FROM Employee The above SQL expression automatically returns the maximum salaried employee”s details, without doing any computation on the developer”s end. Using collections framework in Java, a developer has to use loops and make repeated checks. Another concern is efficiency; as multi-core processors are available at ease, a Java developer has to write parallel code processing that can be pretty error-prone. To resolve such issues, Java 8 introduced the concept of stream that lets the developer to process data declaratively and leverage multicore architecture without the need to write any specific code for it. What is Stream in Java? Stream represents a sequence of objects from a source, which supports aggregate operations. Following are the characteristics of a Stream − Sequence of elements − A stream provides a set of elements of specific type in a sequential manner. A stream gets/computes elements on demand. It never stores the elements. Source − Stream takes Collections, Arrays, or I/O resources as input source. Aggregate operations − Stream supports aggregate operations like filter, map, limit, reduce, find, match, and so on. Pipelining − Most of the stream operations return stream itself so that their result can be pipelined. These operations are called intermediate operations and their function is to take input, process them, and return output to the target. collect() method is a terminal operation which is normally present at the end of the pipelining operation to mark the end of the stream. Automatic iterations − Stream operations do the iterations internally over the source elements provided, in contrast to Collections where explicit iteration is required. Generating Streams in Java With Java 8, Collection interface has two methods to generate a Stream. stream() − Returns a sequential stream considering collection as its source. parallelStream() − Returns a parallel Stream considering collection as its source. List<String> strings = Arrays.asList(“abc”, “”, “bc”, “efg”, “abcd”,””, “jkl”); List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList()); forEach Method Stream has provided a new method ”forEach” to iterate each element of the stream. The following code segment shows how to print 10 random numbers using forEach. Random random = new Random(); random.ints().limit(10).forEach(System.out::println); map Method The ”map” method is used to map each element to its corresponding result. The following code segment prints unique squares of numbers using map. List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5); //get list of unique squares List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList()); filter Method The ”filter” method is used to eliminate elements based on a criteria. The following code segment prints a count of empty strings using filter. List<String>strings = Arrays.asList(“abc”, “”, “bc”, “efg”, “abcd”,””, “jkl”); //get count of empty string int count = strings.stream().filter(string -> string.isEmpty()).count(); limit Method The ”limit” method is used to reduce the size of the stream. The following code segment shows how to print 10 random numbers using limit. Random random = new Random(); random.ints().limit(10).forEach(System.out::println); sorted Method The ”sorted” method is used to sort the stream. The following code segment shows how to print 10 random numbers in a sorted order. Random random = new Random(); random.ints().limit(10).sorted().forEach(System.out::println); Parallel Processing parallelStream is the alternative of stream for parallel processing. Take a look at the following code segment that prints a count of empty strings using parallelStream. List<String> strings = Arrays.asList(“abc”, “”, “bc”, “efg”, “abcd”,””, “jkl”); //get count of empty string long count = strings.parallelStream().filter(string -> string.isEmpty()).count(); It is very easy to switch between sequential and parallel streams. Collectors Collectors are used to combine the result of processing on the elements of a stream. Collectors can be used to return a list or a string. List<String>strings = Arrays.asList(“abc”, “”, “bc”, “efg”, “abcd”,””, “jkl”); List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList()); System.out.println(“Filtered List: ” + filtered); String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(“, “)); System.out.println(“Merged String: ” + mergedString); Statistics With Java 8, statistics collectors are introduced to calculate all statistics when stream processing is being done. List numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5); IntSummaryStatistics stats = numbers.stream().mapToInt((x) -> x).summaryStatistics(); System.out.println(“Highest number in List : ” + stats.getMax()); System.out.println(“Lowest number in List : ” + stats.getMin()); System.out.println(“Sum of all numbers : ” + stats.getSum()); System.out.println(“Average of all numbers : ” + stats.getAverage()); Java Streams Example Create the following Java program using any editor of your choice in, say, C:> JAVA. Java8Tester.java import java.util.ArrayList; import java.util.Arrays; import java.util.IntSummaryStatistics; import java.util.List; import java.util.Random; import java.util.stream.Collectors; import java.util.Map; public class Java8Tester { public static void main(String args[]) { System.out.println(“Using Java 7: “); // Count empty strings List<String> strings = Arrays.asList(“abc”, “”, “bc”, “efg”, “abcd”,””, “jkl”); System.out.println(“List: ” +strings); long count = getCountEmptyStringUsingJava7(strings); System.out.println(“Empty Strings: ” + count); count = getCountLength3UsingJava7(strings); System.out.println(“Strings of length 3: ” + count); //Eliminate empty string List<String> filtered = deleteEmptyStringsUsingJava7(strings); System.out.println(“Filtered List: ” + filtered); //Eliminate empty string and join using comma. String mergedString = getMergedStringUsingJava7(strings,”, “); System.out.println(“Merged String: ” + mergedString); List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5); //get list of square of distinct numbers List<Integer> squaresList = getSquares(numbers); System.out.println(“Squares List: ” + squaresList); List<Integer> integers = Arrays.asList(1,2,13,4,15,6,17,8,19); System.out.println(“List: ” +integers); System.out.println(“Highest number in List : ” + getMax(integers)); System.out.println(“Lowest number in List : ” + getMin(integers)); System.out.println(“Sum of all numbers : ” + getSum(integers)); System.out.println(“Average of all numbers : ” + getAverage(integers)); System.out.println(“Random Numbers: “); //print ten random numbers Random random = new Random(); for(int i = 0; i < 10; i++) { System.out.println(random.nextInt()); } System.out.println(“Using Java 8: “); System.out.println(“List: ” +strings); count = strings.stream().filter(string->string.isEmpty()).count(); System.out.println(“Empty Strings: ” + count); count = strings.stream().filter(string -> string.length() == 3).count(); System.out.println(“Strings of length 3: ” + count); filtered = strings.stream().filter(string ->!string.isEmpty()).collect(Collectors.toList()); System.out.println(“Filtered List: ” + filtered); mergedString = strings.stream().filter(string ->!string.isEmpty()).collect(Collectors.joining(“, “)); System.out.println(“Merged String: ” + mergedString); squaresList = numbers.stream().map( i ->i*i).distinct().collect(Collectors.toList()); System.out.println(“Squares List: ” + squaresList); System.out.println(“List: ” +integers); IntSummaryStatistics stats =

Java – EnumSet

Java EnumSet Class ”; Previous Next Introduction The Java EnumSet class is a specialized Set implementation for use with enum types. Following are the important points about EnumSet − All of the elements in an enum set must come from a single enum type that is specified, explicitly or implicitly, when the set is created. Enum sets are represented internally as bit vectors. EnumSet is not synchronized.If multiple threads access an enum set concurrently, and at least one of the threads modifies the set, it should be synchronized externally. Class declaration Following is the declaration for java.util.EnumSet class − public abstract class EnumSet<E extends Enum<E>> extends AbstractSet<E> implements Cloneable, Serializable Class methods Sr.No. Method & Description 1 static <E extends Enum<E>> EnumSet<E> allOf(Class<E> elementType) This method creates an enum set containing all of the elements in the specified element type. 2 EnumSet<E> clone() This method returns a copy of this set. 3 static <E extends Enum<E>> EnumSet<E> complementOf(EnumSet<E> s) This method creates an enum set with the same element type as the specified enum set, initially containing all the elements of this type that are not contained in the specified set. 4 static <E extends Enum<E>> EnumSet<E> copyOf(Collection<E> c) This method creates an enum set initialized from the specified collection. 5 static <E extends Enum<E>> EnumSet<E> copyOf(EnumSet<E> s) This method creates an enum set with the same element type as the specified enum set, initially containing the same elements (if any). 6 static <E extends Enum<E>> EnumSet<E> noneOf(Class<E> elementType) This method creates an empty enum set with the specified element type. 7 static <E extends Enum<E>> EnumSet<E> of(E e) This method creates an enum set initially containing the specified element. 8 static <E extends Enum<E>> EnumSet<E> range(E from, E to) This method creates an enum set initially containing all of the elements in the range defined by the two specified endpoints. Methods inherited This class inherits methods from the following classes − java.util.AbstractSet java.util.AbstractCollection java.util.Object java.util.Set Creating an EnumSet Example The following example shows the usage of Java EnumSet of(E) method to populate the EnumSet instance. We”ve created a enum Numbers. Then a EnumSet instance is created using a enum value and resulted enumSet is printed. package com.tutorialspoint; import java.util.EnumSet; public class EnumSetDemo { // create an enum public enum Numbers { ONE, TWO, THREE, FOUR, FIVE }; public static void main(String[] args) { // create a set that contains an enum EnumSet<Numbers> set = EnumSet.of(Numbers.ONE); // print set System.out.println(“Set:” + set); } } Let us compile and run the above program, this will produce the following result − Set:[ONE] Print Page Previous Next Advertisements ”;