Tuesday, 30 April 2019

LinkedHashSet in Java With Examples

LinkedHashSet in Java is also one of the implementation of the Set interface. Actually LinkedHashSet class in Java extends the HashSet class and uses methods of that class for its operations.

Just like other implementations of the Set interface HashSet and TreeSet, LinkedHashSet also stores unique elements. How LinkedHashSet differs from the HashSet in Java is that it maintains the insertion-order of the elements; that is elements in the LinkedHashSet are stored in the sequence in which they are inserted. Note that insertion order is not affected if an element is re-inserted into the set.


How is LinkedHashSet implemented in Java

LinkedHashSet is the Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries.

If you have idea about how HashSet works internally in Java, you must be knowing internally HashSet uses HashMap for storing its elements. Same way LinkedHashSet class in Java internally uses LinkedHashMap and calls the methods of HashSet class for all the operations.

Some of the important points about LinkedHashSet in Java are as follows-

  • LinkedHashSet is an ordered set and maintains the insertion order of its elements.
  • LinkedHashSet only stores unique elements, no duplicates.
  • LinkedHashSet permits one null element to be added.
  • LinkedHashSet implementation is not synchronized hence not thread safe. If LinkedHashSet is to be used in a multi-threaded environment where it is accessed and modified concurrently then it must be synchronized externally. That can be done by wrapping the set with in Collections.synchronizedSet method.
  • The iterators returned by LinkedHashSet's iterator method are fail-fast: if the set is modified at any time after the iterator is created, in any way except through the iterator's own remove method, the Iterator throws a ConcurrentModificationException.

Java LinkedHashSet Constructors

  • LinkedHashSet()- Constructs a new, empty linked hash set with the default initial capacity (16) and load factor (0.75).
  • LinkedHashSet(int initialCapacity)- Constructs a new, empty linked hash set with the specified initial capacity and the default load factor (0.75).
  • LinkedHashSet(int initialCapacity, float loadFactor)- Constructs a new, empty linked hash set with the specified initial capacity and load factor.
  • LinkedHashSet(Collection<? extends E> c)- Constructs a new linked hash set with the same elements as the specified collection.

Just take any of the Constructor of the LinkedHashSet and you will see all those contructors will ultimatey call the Constructor of the HashSet where map will be initialized as a LinkedHashMap.

For example if we take the following constructor of the LinkedHashSet-
public LinkedHashSet(int initialCapacity, float loadFactor) {
    super(initialCapacity, loadFactor, true);
}

Which in turns call a constructor in HashSet and instantiates a LinkedHashMap-

HashSet(int initialCapacity, float loadFactor, boolean dummy) {
    map = new LinkedHashMap<>(initialCapacity, loadFactor);
}

LinkedHashSet creation Java example

Following example shows how to create a LinkedHashSet and add elements to it.

public class LinkedHSDemo {

    public static void main(String[] args) {
        // Using Diamond operator Which is available from Java 7
        // Use LinkedHashSet<String> if using less than version 7
        Set<String> citySet = new LinkedHashSet<>();
        
        citySet.add("Delhi");
        citySet.add("Mumbai");
        citySet.add(null);
        citySet.add("Bangalore");
        citySet.add("Delhi");
        citySet.add(null);
        
        // Iterating the Set
        for(String str : citySet){
            System.out.println("" + str);
        }     
    }
}

Output

Delhi
Mumbai
null
Bangalore

Points to note here -

  • It can be seen that the insertion order is maintained. While iterating the LinkedHashSet elements are displayed in the order they were inserted.
  • Even though Delhi is inserted twice it is displayed only once which shows that the LinkedHashSet doesn't allow duplicates and insertion order is not affected if an element is re-inserted into the set.
  • Only one null is allowed in the LinkedHashSet, even if I have tried to insert null twice it can be seen that only one is stored.

LinkedHashSet element removal example

public class LinkedHSDemo {

    public static void main(String[] args) {
        Set<String> citySet = new LinkedHashSet<String>();
        // Adding elements
        citySet.add("London");        
        citySet.add("Tokyo");
        citySet.add("New Delhi");
        citySet.add("Beijing");
        citySet.add("Nairobi");
        // checking of set contains that element
        if(citySet.contains("Nairobi")) {
            citySet.remove("Nairobi");
        }
        System.out.println("--LinkedHashSet after removing using remove method--");
        for(String city : citySet){
            System.out.println("City- " + city);        
        }
        //using removeIf method
        citySet.removeIf((String city)->city.equalsIgnoreCase("Tokyo"));
        
        System.out.println("--LinkedHashSet after removing using removeIf method--");
        for(String city : citySet){
            System.out.println("City- " + city);        
        }
        
        System.out.println("Total number of elements in LinkedHashSet- " + citySet.size()); 
    }
}

Output

--LinkedHashSet after removing using remove method--
City- London
City- Tokyo
City- New Delhi
City- Beijing
--LinkedHashSet after removing using removeIf method--
City- London
City- New Delhi
City- Beijing
Total number of elements in LinkedHashSet- 3

LinkedHashSet is not synchronized

LinkedHashSet in Java is not thread safe. In case we need to Synchronize it, it should be synchronized externally. That can be done using the Collections.synchronizedSet method.

Set s = Collections.synchronizedSet(new LinkedHashSet(...));

LinkedHashSet class' iterator is fail-fast

Iterator returned by LinkedHashSet is fail-fast: if the set is modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException.

Performance of LinkedHashSet in Java

The performance of LinkedHashSet is likely to be just slightly below that of HashSet, due to the added expense of maintaining the linked list. But there is one exception: Iteration over a LinkedHashSet requires time proportional to the size of the set, regardless of its capacity. Iteration over a HashSet is likely to be more expensive, requiring time proportional to its capacity as in the case of HashSet based on the Hashing function it may have to go through all the buckets .

Recommendations for learning

  1. Java Programming Masterclass Course
  2. Java In-Depth: Become a Complete Java Engineer!
  3. Spring Framework Master Class Course
  4. Complete Python Bootcamp Course
  5. Python for Data Science and Machine Learning

That's all for this topic LinkedHashSet in Java With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How HashSet Works Internally in Java
  2. TreeSet in Java
  3. EnumSet in Java
  4. How to Sort Elements in Different Order in TreeSet
  5. Java Collections Interview Questions

You may also like -

  1. How to Sort ArrayList of Custom Objects in Java
  2. Difference Between Comparable and Comparator in Java
  3. Difference between ArrayList and LinkedList in Java
  4. How to Create Immutable Class in Java
  5. interface static methods in Java 8
  6. Lambda expression examples in Java 8
  7. Why wait(), notify() and notifyAll() must be called inside a synchronized method or block?
  8. varargs in Java

Java Lambda Expression Callable Example

Since Callable is a functional interface, Java 8 onward it can also be implemented as a lambda expression. This post shows how you can implement Callable interface as a lambda expression in Java.

Suppose you want to have a callable where string is passed and it returns the length of the string.
In this Java code a thread pool of 2 threads is created and then submit method is called with callable object as parameter.

Java Code

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CallableLambda {
    public static void main(String args[]){
        ExecutorService es = Executors.newFixedThreadPool(2);
        getLength(es, "executor");
        getLength(es, "executor service");
        getLength(es, "Scheduled executor service");
        getLength(es, "executors");
        getLength(es, "fork join");
        getLength(es, "callable");    
    }
    
    public static void getLength(ExecutorService es, final String str){
        // callable implemented as lambda expression
        Callable<String> callableObj = () -> {
            StringBuffer sb = new StringBuffer();
            return (sb.append("Length of string ").append(str).append(" is ").
                    append(str.length())).toString();
        };
        
        // submit method
        Future<String> f = es.submit(callableObj);
        
        try {
            System.out.println("" + f.get());
        } catch (InterruptedException | ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

Output

Length of string executor is 8
Length of string executor service is 16
Length of string Scheduled executor service is 26
Length of string executors is 9
Length of string fork join is 9
Length of string callable is 8

Also, if you noticed the  try-catch block in the code,  multi catch statement from Java 7 is used here.

That's all for this topic Java Lambda Expression Callable Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Java Lambda Expression Runnable Example
  2. Java Lambda Expression Comparator Example
  3. Lambda Expression Examples in Java 8
  4. Functional Interface Annotation in Java
  5. Java Lambda Expressions Interview Questions

You may also like -

  1. How to Convert Date And Time Between Different Time-Zones in Java
  2. How to Convert a File to Byte Array
  3. Java Concurrency Interview Questions
  4. Executor and ExecutorService in Java concurrency
  5. Difference between Comparable and Comparator
  6. String join() method in Java 8
  7. interface default methods in Java 8
  8. What is Dependency Injection in Spring

Name Mangling in Python

In Python there are no explicit access modifiers so you can’t mark a class member as public/private. Then the question is how to restrict access to a variable or method outside the class, if required. Class member can be made private (Close to private actually) using a process called name mangling in Python.

Name mangling (Making member private)

In Name mangling process any identifier with at least two leading underscores, at most one trailing underscore is textually replaced with _classname__identifier where classname is the current class name. For example if there is a variable __var it is rewritten by the Python interpreter in the form _classname__var.

Since the name of any such class member (with at least two leading underscores, at most one trailing underscore) changes internally thus it can’t be accessed using the given name. That is the closest Python goes for making a class member private.


Python Name mangling example

Let’s try to clarify name mangling process with examples.

class Person:
    def __init__(self, name, age=0):
        self.name = name
        self.__age = age

    def display(self):
        print(self.name)
        print(self.__age)

person = Person('John', 40)
#accessing using class method
print('Displaying values using class method')
person.display()
#accessing directly from outside
print('Trying to access variables from outside the class ')
print(person.name)
print(person.__age)

Output

Displaying values using class method
John
40
Traceback (most recent call last):
File "F:/NETJS/NetJS_2017/Python/Test/Person.py", line 21, in <module>
Trying to access variables from outside the class 
John
    print(person.__age)
AttributeError: 'Person' object has no attribute '__age'

As you can see variable __age (having two leading underscores) is not accessible from outside the class. Using a method with in the class it can still be accessed.

Same way for a method with two leading underscores.

class Person:
    def __init__(self, name, age=0):
        self.name = name
        self.__age = age

    def __displayAge(self):
        print(self.name)
        print(self.__age)

person = Person('John', 40)
person.__displayAge()

Output

Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Test/Person.py", line 15, in <module>
    person.__displayAge()
AttributeError: 'Person' object has no attribute '__displayAge'

As you can see method is not accessible from outside the class.

How does name change in Name mangling

If you want to verify the rewriting of name in Python name mangling process you can do so using the dir() function.

When a class object is passed as an argument to dir() function, it returns a list of valid attributes for that object.

class Person:
    def __init__(self, name, age=0):
        self.name = name
        self.__age = age

person = Person('John', 40)
print(dir(person))

Output

['_Person__age', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', 
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', 
'__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', 
'__str__', '__subclasshook__', '__weakref__', 'name']

From the output of dir() function for Person object you can see that the __age is rewritten as _Person__age.

Name mangling and method overriding

As per Python docs stated objective of name mangling is to avoid name clashes of names with names defined by subclasses. Name mangling is helpful for letting subclasses override methods without breaking intraclass method calls.

For example consider the following scenario where Parent class is subclassed and there is an overridden method test is the Child class too. From the constructor of Parent class there is a call to test method- self.test()

class Parent:
  def __init__(self):
      print('in init')
      self.test()
  def test(self):
    print('In Parent test method')

class Child(Parent):
  def test(self):
    print('In Child test method')

obj = Child()
obj.test()

Output

in init
In Child test method
In Child test method

As you can see Child test method is getting called both of the times. To avoid that name clash you can create a private copy of the original method.

class Parent:
    def __init__(self):
        print('in init')
        self.__test()
    def test(self):
        print('In Parent test method')

    # private copy
    __test = test

class Child(Parent):
    def test(self):
        print('In Child test method')

obj = Child()
obj.test()

Output

in init
In Parent test method
In Child test method

Accessing name mangled class members

As already stated Python name mangling process rewrites the member name by adding _classname to the member. Thus it is still possible to access the class member from outside the class by using the rewritten name. That is why it is said that Name mangling is the closest to private not exactly private.

class Person:
    def __init__(self, name, age=0):
        self.name = name
        self.__age = age

    def display(self):
        print(self.name)
        print(self.__age)


person = Person('John', 40)

print('Trying to access variables from outside the class ')
print(person.name)
print(person._Person__age)

Output

Trying to access variables from outside the class 
John
40

As you can see private class member is accessed from outside the class by using the name mangled form _ClassName__var.

That's all for this topic Name Mangling in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python Installation on Windows
  2. Encapsulation in Python
  3. Method Overriding in Python
  4. Multiple Inheritance in Python
  5. Local, Nonlocal And Global Variables in Python

You may also like -

  1. Passing Object of The Class as Parameter in Python
  2. Python count() method - Counting Substrings
  3. Marker Interface in Java
  4. How Linked List class works internally in Java
  5. Functional Interfaces in Java
  6. Difference between Checked exception & Unchecked exception
  7. Synchronization in Java multithreading
  8. Race Condition in Java Multi-Threading

Monday, 29 April 2019

Encapsulation in Python

Encapsulation is one of the four fundamental OOPS concepts. The other three being-

What is Encapsulation

The concept of Encapsulation is to keep together the implementation (code) and the data it manipulates (variables). Having proper encapsulation ensures that the code and data both are safe from misuse by outside entity.

Encapsulation in Python

In any object oriented language first step towards encapsulation is the class and encapsulation in Python also starts from a class as the class encapsulates the methods and variables.

When a Python class is created it contains the methods and the variables. Since it’s the code in the methods that operates on the variables, in a properly encapsulated Python class, methods should define how member variables can be used.

But that’s where the things differ a bit in Python from a language like Java where we have access modifiers like public, private. In Python there are no explicit access modifiers and everything written with in the class (methods and variables) are public by default.

For example in the class Person there are two variables as you can see those variables are accessed through a method as well as directly.

class Person:
    def __init__(self, name, age=0):
        self.name = name
        self.age = age

    def display(self):
        print(self.name)
        print(self.age)

person = Person('John', 40)
#accessing using class method
person.display()
#accessing directly from outside
print(person.name)
print(person.age)

Output

John
40
John
40

How to control access

If everything inside a class is public then how to have access control and how to have proper encapsulation in Python?

In Python though there are no explicit access modifiers but using underscores (_) you can make a variable private.

Using single underscore

Using a single leading underscore is merely a convention. A name prefixed with an underscore in Python (as example _name) should be treated as a non-public part of the API (whether it is a function, a method or a data member).

As mentioned it is just a convention and a leading underscore doesn’t actually make any variable or method private or protected. It’s just that if you see a variable or method with a leading underscore in Python code you should follow the convention that it should be used internally with in a class.

For example in class Person if age variable is changed and it is prefixed with underscore.

class Person:
    def __init__(self, name, age=0):
        self.name = name
        self._age = age

    def display(self):
        print(self.name)
        print(self._age)

person = Person('John', 40)
#accessing using class method
person.display()
#accessing directly from outside
print(person.name)
print(person._age)

Output

John
40
John
40

As you can see these variables can still be accessed from outside the class.

Using double underscore (making it private)

If you really want to make a class member (member or variable) private in Python you can do it by prefixing a variable or method with double underscores. Here note that Python provides a limited support for private modifier using a mechanism called name mangling and it is still possible to access such class member from outside the class.

In Python any identifier of the form __var (at least two leading underscores, at most one trailing underscore) is rewritten by the Python interpreter in the form _classname__var, where classname is the current class name. This mechanism of name changing is known as name mangling in Python.

For example in class Person age variable is changed and it is prefixed with two leading underscores.

class Person:
    def __init__(self, name, age=0):
        self.name = name
        self.__age = age

    def display(self):
        print(self.name)
        print(self.__age)

person = Person('John', 40)
#accessing using class method
person.display()
#accessing directly from outside
print('Trying to access variables from outside the class ')
print(person.name)
print(person.__age

Output

John
40
Trying to access variables from outside the class
John
Traceback (most recent call last):
  File "Person.py", line 16, in <module>
    print(person.__age)
AttributeError: 'Person' object has no attribute '__age'

As you can see variables can still be accessed using the method which is part of the class but age (which is a private variable) can’t be accessed directly from outside now.

Using getter and setter methods to access private variables

To access and change private variables accessor (getter) methods and mutator (setter methods) should be used which are part of the class.

class Person:
    def __init__(self, name, age=0):
        self.name = name
        self.__age = age

    def display(self):
        print(self.name)
        print(self.__age)

    def getAge(self):
        print(self.__age)

    def setAge(self, age):
        self.__age = age

person = Person('John', 40)
#accessing using class method
person.display()
#changing age using setter
person.setAge(45)
person.getAge()

Output

John
40
45

That's all for this topic Encapsulation in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python Installation on Windows
  2. Python First Program - Hello World
  3. Method Overriding in Python
  4. Python for Loop With Examples
  5. self in Python

You may also like -

  1. Name Mangling in Python
  2. Constructor in Python - __init__() function
  3. How to read file from the last line in Java
  4. Marker Interface in Java
  5. How Linked List class works internally in Java
  6. Functional Interfaces in Java
  7. Difference between Checked exception & Unchecked exception
  8. Race Condition in Java Multi-Threading

Sunday, 28 April 2019

Thread Priority in Java Multi-Threading

When we talk about thread we use terms like concurrent threads or threads executing concurrently. But in reality threads also run one at a time (at least in a single CPU system), threads are given CPU cycle in a time shared manner to simulate concurrency. The order in which multiple threads will be executed is decided by thread scheduler and thread priority is used by the thread scheduler to make that decision. This article is about the thread priorities available in Java multi-threading and how to get and set Java thread priority.

Java Thread Priority

When a thread is created in Java, it inherits its priority from the thread that creates it. Thread's priority can be modified at any time after its creation using the setPriority() method which is a member of Thread class.

General form of setPriority() method

public final void setPriority(int newPriority)

Here newPriority specifies the new thread priority setting for the calling thread. Thread priority in Java ranges from 1 (least important) to 10 (most important) and the default priority level is 5 .

In Java Thread class, three constants are provided to define min, max and default priority of a thread.

     /**
     * The minimum priority that a thread can have.
     */
    public final static int MIN_PRIORITY = 1;

    /**
     * The default priority that is assigned to a thread.
     */
    public final static int NORM_PRIORITY = 5;

    /**
     * The maximum priority that a thread can have.
     */
    public final static int MAX_PRIORITY = 10;

Let's write some code to see Java thread priority in action. First we'll write a program where no priorities are set so each thread will have the default priority (i.e. 5).

Getting thread priority in Java

If you want to check priority of a thread that can be done using getPriority() method.

  • int getPriority()- Returns this thread's priority.
//This class' shared object will be accessed by threads
class LoopValues implements Runnable{

    @Override
    public void run() {
 System.out.println(Thread.currentThread().getName() + 
            " Priority is " + Thread.currentThread().getPriority());
        for (int i = 1; i <= 10; i++) {
            System.out.println(Thread.currentThread().getName() + " : " + i);
        }      
    }
}

public class ThreadPriorityDemo {
    public static void main(String[] args) {
        Thread thread1 = new Thread(new LoopValues(), "Thread-1");
        Thread thread2 = new Thread(new LoopValues(), "Thread-2");            
        thread1.start();
        thread2.start();           
        try {
            
            //Wait for the threads to finish
            thread1.join();
            thread2.join();            
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }            
        System.out.println("Done with looping values");
    }
}

Output

Thread-1 Priority is 5
Thread-2 Priority is 5
Thread-1 : 1
Thread-1 : 2
Thread-1 : 3
Thread-1 : 4
Thread-2 : 1
Thread-2 : 2
Thread-2 : 3
Thread-2 : 4
Thread-2 : 5
Thread-2 : 6
Thread-2 : 7
Thread-2 : 8
Thread-2 : 9
Thread-2 : 10
Thread-1 : 5
Thread-1 : 6
Thread-1 : 7
Thread-1 : 8
Thread-1 : 9
Thread-1 : 10
Done with looping values

Here it can be seen that output has a mix of both the threads. Please note that the output may vary with each run.

Setting thread priority Java example

Now we'll set the thread priorities so that one thread has the MAX_PRIORITY (10) and another has the MIN_PRIORITY (1).

//This class' shared object will be accessed by threads
class LoopValues implements Runnable{

    @Override
    public void run() {
 System.out.println(Thread.currentThread().getName() + 
            " Priority is " + Thread.currentThread().getPriority());
        for (int i = 1; i <= 10; i++) {
            System.out.println(Thread.currentThread().getName() + " : " + i);
        }  
    }
}

public class ThreadPriorityDemo {
    public static void main(String[] args) {
        Thread thread1 = new Thread(new LoopValues(), "Thread-1");
        Thread thread2 = new Thread(new LoopValues(), "Thread-2");      
        thread1.setPriority(Thread.MAX_PRIORITY);
        thread2.setPriority(Thread.MIN_PRIORITY);
        thread1.start();
        thread2.start();           
        try {
            //Wait for the threads to finish
            thread1.join();
            thread2.join();
            
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }       
        System.out.println("Done with looping values");
    }
}

Output

Thread-1 Priority is 10
Thread-1 : 1
Thread-1 : 2
Thread-1 : 3
Thread-1 : 4
Thread-1 : 5
Thread-1 : 6
Thread-1 : 7
Thread-1 : 8
Thread-1 : 9
Thread-1 : 10
Thread-2 Priority is 1
Thread-2 : 1
Thread-2 : 2
Thread-2 : 3
Thread-2 : 4
Thread-2 : 5
Thread-2 : 6
Thread-2 : 7
Thread-2 : 8
Thread-2 : 9
Thread-2 : 10
Done with looping values

It can be seen that the thread which has the highest priority finishes first then the second thread starts its execution. Please note that even with this priority setting there may be a mixed output or the thread with the min priority may execute first. That brings us to the next section why we can't rely that much on thread priority in Java.

Caution with thread priority in Java

Thread priority rules are dependent on the host platform (native OS). Host platform may have different priorities for the threads which may be more than what priorities are defined in Java or may be less than that. Java run time system maps the thread priorities to the priority levels of the host platform. So JVM may schedule a thread according to the priority defined in Java multithreading but when that thread actually gets the CPU cycle also depends upon the priorities defined by the host platform.

That's all for this topic Thread Priorities in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Thread States in Java Multi-Threading
  2. Synchronization in Java Multi-Threading
  3. Volatile in Java
  4. What if run() Method Called Directly Instead of start() Method
  5. Java Multi-Threading Interview Questions

You may also like -

  1. Difference Between Abstract Class And Interface in Java
  2. static method overloading or overriding in Java
  3. strictfp in Java
  4. Reflection in Java
  5. Difference Between Checked & Unchecked Exception in Java
  6. try-with-resources in Java 7
  7. CopyOnWriteArrayList in Java
  8. How to Read File From The Last Line in Java

Saturday, 27 April 2019

strictfp in Java

strictfp is a keyword in Java that restricts floating-point calculations to ensure portability. As different platforms can handle different floating-point calculation precision and greater range of values than the Java specification requires, that may produce different output on different platforms. Using strictfp guarantees that results of floating-point calculations are identical on all platforms.

Usage of strictfp in Java

The strictfp command was introduced in Java with JVM 1.2 and is available for use on all currently updated Java Virtual Machines.

Floating-point calculations may vary on different platforms because of the precision used like the standard 32 bit precision, 64 bit precision, 80-bit double extended on x86 or x86-64 platforms. strictfp is used, in case, where a programmer might need every platform to have precisely the same floating-point behaviour, even on platforms that could handle greater precision.

strictfp in Java can be used with-

strictfp can not be used with-

strictfp Java example

strictfp class StrictfpDemo {

    float f = 9.678f;
    
    strictfp public void displayValue(){
        System.out.println(f);
    }

    public static void main(String[] args) {
      StrictfpDemo strictfpDemo = new StrictfpDemo();
      strictfpDemo.displayValue();
    }
}

It can be seen in the program how strictfp modifier is used with the class and the method.

Reference:https://en.wikipedia.org/wiki/Strictfp

That's all for this topic strictfp in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. final Keyword in Java With Examples
  2. static Keyword in Java With Examples
  3. this Keyword in Java With Examples
  4. super Keyword in Java With Examples
  5. Core Java Basics Interview Questions

You may also like-

  1. abstract Class in Java
  2. static import in Java
  3. Automatic numeric type promotion in Java
  4. BigDecimal in Java
  5. Check if given strings are anagram or not
  6. Treemap in Java
  7. Deadlock in Java multi-threading
  8. CountDownLatch in Java concurrency

String Comparison in Java equals(), compareTo(), startsWith() Methods

In String class in Java there are number of methods provided to compare the Strings or the portion of the strings. This post shows some of the most used methods for comparing Strings in Java and also Java examples using these methods for comparing two strings.


String comparison using equals() and equalsIgnoreCase() methods

  • boolean equals(Object anObject)- This method is used to compare the content of two strings. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
  • boolean equalsIgnoreCase(String anotherString)- Comparison of strings using equals() method is case sensitive, if you want case considerations to be ignored then use equalsIgnoreCase method. When two strings are compared using this method they are considered equal ignoring case if they are of the same length and corresponding characters in the two strings are equal ignoring case.

Example code

public class StringComparison {

 public static void main(String[] args) {
  String str = "This is a test string";
  String str1 = new String("This");
  System.out.println("String for comparison -- " + str.substring(0, 4));
  // Should be true
  System.out.println(str.substring(0, 4).equals("This"));
  // will be false, equals is case sensitive
  System.out.println(str.substring(0, 4).equals("this"));
  
  // returns true, case is ignored
  System.out.println(str.substring(0, 4).equalsIgnoreCase("this"));
  // returns true
  System.out.println(str1.equalsIgnoreCase("this"));
 }
}

Output

String for comparison -- This
true
false
true
true

Here original string is substringed to give a part of the String (“This”). That part is then used for comparison with another string (str1). Even when a new String is created which will have different reference, equals or equalsIgnoreCase will return true as content is matched here not reference.

String comparison using compareTo() and compareToIgnoreCase() methods

  • int compareTo(String anotherString)- Compares two strings lexicographically. Returns an integer indicating whether this string is greater than (result is > 0), equal to (result is = 0), or less than (result is < 0) the argument.
  • int compareToIgnoreCase(String str)- Compares two strings lexicographically, ignoring differences in case. Returns an integer indicating whether this string is greater than (result is > 0), equal to (result is = 0), or less than (result is < 0) the argument.

In lexicographical comparison if two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different, or both.

If character is different at some position then, compareTo returns the difference of the two character values, As Example if you are comparing run with sun then first char itself is different and difference between them is 1 so in that case -1 is returned.

If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case, compareTo returns the difference of the lengths of the strings.

To sum it up when two strings are compared using compareTo or compareToIgnoreCase methods, an integer value is returned which may be a positive or negative integer value or 0. Compared strings are equal if 0 is returned otherwise strings are not equal.

Example code

public class StringComparison {

    public static void main(String[] args) {
        String str1 = "run";
        String str2 = new String("run");
        String str3 = "gun";
        String str4 = "sun";
        
        //equal so returns 0
        System.out.println(str1.compareTo(str2));
        // Comparison with in a condition
        // that's how generally used 
        if(str1.compareTo(str2) == 0){
            System.out.println("str1 is equal to str2");
        }else{
            System.out.println("str1 is not equal to str2");
        }
        
        //str1 > str3 so returns positive integer
        System.out.println(str1.compareTo(str3));
        // with condition
        if(str1.compareTo(str3) > 0){
            System.out.println("str1 is greater than str3");
        }else{
            System.out.println("str1 is less than str3");
        }
        
        // str1 < str4 so returns negative integer
        System.out.println(str1.compareTo(str4));       
    }
}

Output

0
str1 is equal to str2
11
str1 is greater than str3
-1

String comparison using startsWith() and endsWith() methods

Using startsWith() and endsWith() methods you can compare a portion of a String.

  • boolean startsWith(String prefix)- Returns true if this string begins with the substring specified as an argument to the method.
  • boolean startsWith(String prefix, int offset)- Considers the string beginning at the index offset, and returns true if it begins with the substring specified as an argument.
  • boolean endsWith(String suffix)- Returns true if this string ends with the substring specified as an argument to the method.

Example code

public class StringComparison {

 public static void main(String[] args) {
  String str = "This is a test string";
  // Should be true
  System.out.println(str.startsWith("This"));
  // test start at index 10, so returns true
  System.out.println(str.startsWith("test", 10));
  
  // returns false
  System.out.println(str.endsWith("test"));
  // returns true
  System.out.println(str.endsWith("test string"));
  // returns true
  System.out.println(str.endsWith("string")); 
 }
}

Output

true
true
false
true
true

Using regionMatches() method for String comparison

  • boolean regionMatches(int toffset, String other, int ooffset, int len)- Tests whether the specified region of this string matches the specified region of the String argument.
    Region is of length len and begins at the index toffset for this string and ooffset for the other string. This method is case sensitive.
  • boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)– Here first argument indicates whether case should be ignored; if true, case is ignored when comparing characters.

Example code

public class StringComparison {

 public static void main(String[] args) {
  String str1 = "This is an example string";
  String str2 = new String("example");
  String str3 = "Example";
  // returns true
  System.out.println(str1.regionMatches(11, str2, 0, str2.length()));
  // returns false
  System.out.println(str1.regionMatches(11, str3, 0, str3.length()));
  // returns true as case is ignored
  System.out.println(str1.regionMatches(true, 11, str3, 0, str3.length()));
 }

}

Output

true
false
true

Here in the first comparison using regionMatches() method the task is to compare “example” in string str1 with the string str2. Region extracted from String str1 starts at index 11 and length for the region is 7 which makes it "example". Comparison is to be done with the string str2 so that is the second argument. In str2 offset is 0. Here region to be compared is the complete length of string str2 so str2.length() method is used.

In second case everything is same except the matched string str3 which has the content “Example”. Since method is case sensitive so returns false.

In third case first argument is passed as true so the case is ignored while comparing. That is why true is returned even when str1 and str3 are compared.

That's all for this topic String Comparison in Java equals(), compareTo(), startsWith() Methods. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related topics

  1. String in Java Tutorial
  2. How to Reverse a String in Java
  3. How to Add Double Quotes to a String - Java Program
  4. String And Thread-Safety in Java
  5. Java String Interview Questions

You may also like -

  1. How to format date in Java using SimpleDateFormat
  2. Marker interface in Java
  3. How and why to synchronize ArrayList in Java
  4. LinkedHashMap in Java
  5. How Linked List class works internally in Java
  6. Difference Between CountDownLatch And CyclicBarrier in Java
  7. LinkedBlockingQueue in Java Concurrency
  8. interface default methods in Java 8

Friday, 26 April 2019

Main Thread in Java

When a Java program starts, one thread starts running immediately that thread is known as main thread in Java.

If you run the following program where you have not created any thread, still on printing the thread name you can see that the thread name is displayed as “main”. This is the main thread which started running automatically.

public class ThreadDemo {
    public static void main(String[] args) { 
     System.out.println("Thread name- " + Thread.currentThread().getName());
    }
}

Output

Thread name- main

Main thread - Java multi-threading

A thread spawned from the current thread inherits the following properties from the parent thread-

Since main thread is the first thread that is started so other threads are spawned from the context of the main thread and other threads will inherit above mentioned properties from main thread.

Also note that the JVM terminates only after all the non-daemon threads have finished execution. In your application if you have other non-daemon threads executing then main thread can terminate before those threads. So, main thread is the first to start in your application but it doesn’t have to be the last to finish.

Here is a Java example of main thread where three more threads are spawned. Since all the three threads are spawned from main thread so they should have same priority and should be non-daemon threads. Main thread object is passed to the spawned threads to keep checking that main thread is alive or not using isAlive() method.

class NumThread implements Runnable{
    Thread mainThread;
    public NumThread(Thread thread) {
        this.mainThread = thread;
    }
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+ " Priority " 
         + Thread.currentThread().getPriority());
        System.out.println("Is Daemon Thread " + Thread.currentThread().isDaemon());
        for (int i = 0; i < 5; i++) {             
            System.out.println(Thread.currentThread().getName() + " : " + i);
        } 
        System.out.println("Thread name " + mainThread.getName());
        System.out.println("Main Thread Status " + mainThread.isAlive());     
    }
}

public class MainThreadDemo {

    public static void main(String[] args) {
        System.out.println("Thread name- " + Thread.currentThread().getName());
        System.out.println("Thread Status " + Thread.currentThread().isAlive());
        System.out.println("Thread Priority " + Thread.currentThread().getPriority());
        System.out.println("Is Daemon Thread " + Thread.currentThread().isDaemon());
         // Creating threads
        Thread t1 = new Thread(new NumThread(Thread.currentThread()), "Thread-1");
        Thread t2 = new Thread(new NumThread(Thread.currentThread()), "Thread-2");
        Thread t3 = new Thread(new NumThread(Thread.currentThread()), "Thread-3");
        t1.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        t2.start(); 
        t3.start();
        System.out.println("Thread Status " + Thread.currentThread().isAlive());
    }
}

Output

Thread name- main
Thread Status true
Thread Priority 5
Is Daemon Thread false
Thread-1 Priority 5
Is Daemon Thread false
Thread-1 : 0
Thread-1 : 1
Thread-1 : 2
Thread-1 : 3
Thread-1 : 4
Thread name main
Main Thread Status true
Thread Status true
Thread-2 Priority 5
Is Daemon Thread false
Thread-2 : 0
Thread-2 : 1
Thread-2 : 2
Thread-3 Priority 5
Is Daemon Thread false
Thread-2 : 3
Thread-2 : 4
Thread name main
Main Thread Status false
Thread-3 : 0
Thread-3 : 1
Thread-3 : 2
Thread-3 : 3
Thread-3 : 4
Thread name main
Main Thread Status false

As you can see for all the threads, thread priority is 5 which is same as the priority of main thread. Also all the spawned threads are non-daemon threads. You can also see from the displayed messages that main thread died while thread-2 and thread-3 were still executing.

That's all for this topic Main Thread in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Creating Thread in Java
  2. Thread States in Java Multi-Threading
  3. Race Condition in Java Multi-Threading
  4. Why wait(), notify() And notifyAll() Must be Called Inside a Synchronized Method or Block
  5. Volatile in Java

You may also like -

  1. Difference Between Encapsulation And Abstraction in Java
  2. static Reference to The Non-static Method or Field Error
  3. Difference Between throw And throws in Java Exception Handling
  4. CallableStatement Interface in Java-JDBC
  5. Reflection in Java
  6. Nested Class And Inner Class in Java
  7. Object Cloning in Java
  8. Just In Time Compiler (JIT) in Java

Thursday, 25 April 2019

Ternary Operator in Java

Java includes a conditional operator known as ternary operator (?:), which can be thought of as a shorthand for an if-else statement. This operator is known as the ternary operator because it uses three operands.

General form of ternary operator in Java

boolean-exp ? expression2 : expression3

If boolean expression evaluates to true then expression2 is evaluated and its value becomes the result of the operator; otherwise (if boolean expression is false) expression3 is evaluated and its value becomes the result of the operator.

As example if you have this statement-

int result = someCondition ? value1 : value2;

The statement should be read as: "If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result."

Note that in Java Ternary operator both expression2 and expression3 should return the value of same (or compatible) type.

Usage of Java ternary operator

Though switch-case statement in Java provides performance improvement over if-else statement there is no performance improvement if ternary operator in Java is used over an if-else statement but it makes the code more readable and terse.

As example -

int val = (i > 10) ? i * 5 : i * 10;

Here val is assigned the value (i * 5) if i is greater than 10 otherwise val is assigned the value (i * 10).

Writing the same thing using if-else will be a multiple line affair.

 
 if(i > 10){
    val = i * 5;
}else{
    val = i * 10;
}

If you were to write a method where value is returned using the same logic, with ternary operator the method will look like -

 
public int getValue(int i){
 return (i > 10) ? i * 5 : i * 10;
}

In this case if-else statement can also be made more compact -

 
public static int getValue(int i){
    if(i > 10)
        return i * 5;
    return i * 10;
}

Not its up to you to decide what looks more readable. I feel once you get a grip over ternary operator it will always be more readable.

Another example – This example uses String expression and prints a message based on the value of the string.

 
String day = "saturday";
System.out.println(((day.equalsIgnoreCase("saturday") || day.equalsIgnoreCase("sunday"))
    ? "weekend! time to party!" : "Working day"));

Output

weekend! time to party!

Nested ternary operator

Ternary operator in Java can be nested but doing that considerably decreases the readability.

As example if you have the logic that number of transactions in a week is-

upto 5 means ok, 
more than 5 and less than 10 means notify the user 
more than 10 means alarm!!

Then you can use the nested ternary operator

String noOfTransactions = (i < 5) ? "ok" : (i > 5 && i < 10) ? "notify" : "alarm";

Generally it is not advisable to use nested ternary operator as it defeats the purpose of making the code more readable in contrast it makes it look more complex and confusing in most of the cases.

That's all for this topic Ternary Operator in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Switch-Case Statement in Java
  2. instanceof Operator in Java
  3. Arithmetic And Unary Operators in Java
  4. String in Java
  5. Core Java Basics Interview Questions

You may also like -

  1. Java pass by value or pass by reference
  2. Inheritance in Java
  3. Abstraction in Java
  4. Difference between Encapsulation and Abstraction in Java
  5. Initializer block in Java
  6. HashMap Vs LinkedHashMap Vs TreeMap in Java
  7. Difference between ArrayList and LinkedList in Java
  8. Difference between CountDownLatch and CyclicBarrier
  9. Lambda expressions in Java 8

Wednesday, 24 April 2019

Spliterator in Java

Spliterator in Java just like iterator, is used for traversing the elements of a source. The source of elements covered by a Spliterator could be, for example, an array, a Collection, an IO channel, or a generator function.

As the name suggests, Spliterator in Java can split the source and partition off some of its elements as another Spliterator, to be used in possibly-parallel operations. That way a huge data source can be divided into small sized units that can be traversed and processed in parallel.


Java Spliterator interface

Spliterator is a generic interface in Java defined as -

Interface Spliterator<T>

Where T is the type of elements returned by this Spliterator.

Java Spliterator methods

Though spliterator will increase performance by traversing the collection in parallel but you can also use spliterator even if you are not using parallel execution.

If you use iterator you have to use two methods hasNext() to ensure that there is next element and then next() method to use that element. Spliterator in Java provides methods that combine these two methods into one and making it more convenient to use.

Some of the frequently used methods of Spliterator in Java are -

  • tryAdvance() - If a remaining element exists, performs the given action on it, returning true; else returns false. Its form is -
    tryAdvance(Consumer<? super T> action)
    
    Here action is an instance of Consumer, which is a functional interface, it specifies the function that has to be applied on the next element while traversing the collection (or any other source).
  • forEachRemaining - Performs the given action for each remaining element, sequentially in the current thread, until all elements have been processed or the action throws an exception. Its form is -
    default void forEachRemaining(Consumer<? super T> action)
    
  • estimateSize() - Returns an estimate of the number of elements that would be encountered by forEachRemaining traversal, or returns Long.MAX_VALUE if infinite, unknown, or too expensive to compute. Its form is -
    long estimateSize()
    
  • trySplit() - If current spliterator can be partitioned a new spliterator is created, it partitions the elements of the source so that new spliterator traverse one of the partition while original spliterator traverses the other partition.
  • characteristics() - Returns a set of characteristics of this Spliterator and its elements.

Spliterator characteristics

A Spliterator also reports a set of characteristics() of its structure, source, and elements from among ORDERED, DISTINCT, SORTED, SIZED, NONNULL, IMMUTABLE, CONCURRENT, and SUBSIZED.

These characteristics are defined as constant fields in the Spliterator interface.

Read more about them here - https://docs.oracle.com/javase/8/docs/api/java/util/Spliterator.html#characteristics--

To see constant values - https://docs.oracle.com/javase/8/docs/api/constant-values.html#java.util.Spliterator

Using characteristics() method will give you a result represented as ORed values of the characterstics relevant for the given source.

Java Spliterator example

If you have a list of names and you want to iterate it and print the names, using iterator it can be done as follows-

public class IteratorDemo {

    public static void main(String[] args) {
        List<String> nameList = Arrays.asList("Ram", "Sheila", "Mukesh", "Rani", 
        "Nick", "Amy", "Desi", "Margo");
        Iterator<String> itr = nameList.iterator();
        while (itr.hasNext()) {
            System.out.println("name - " + itr.next());   
        }
    }
}

Same thing can be done using spliterator like this-

public class SpliteratorDemo {

    public static void main(String[] args) {
        List<String> nameList = Arrays.asList("Ram", "Sheila", "Mukesh", "Rani", 
        "Nick", "Amy", "Desi", "Margo");
        Spliterator<String> splitStr = nameList.spliterator();
        while(splitStr.tryAdvance((n) -> System.out.println("name - " + n)));
    }

}

You can see, with Spliterator, you need to use only one method tryAdvance() which combines both hasNext() and next() methods of the iterator.

Java Spliterator forEachRemaining method example

If you want to convert all the names to lowercase you can use forEachRemaining method.

import java.util.Arrays;
import java.util.List;
import java.util.Spliterator;

public class SpliteratorDemo {

    public static void main(String[] args) {
        List<String> nameList = Arrays.asList("Ram", "Sheila", "Mukesh", "Rani", 
          "Nick", "Amy", "Desi", "Margo");
        Spliterator<String> splitStr = nameList.spliterator();
        splitStr.forEachRemaining( 
            (n) -> {
                String x = n.toLowerCase();
                System.out.println("" + x);
            }
        );
    }

}

Java Spliterator trySplit method example

If you want to split the original spliterator so that you can traverse the element in parallel.

import java.util.Arrays;
import java.util.List;
import java.util.Spliterator;

public class SpliteratorDemo {

    public static void main(String[] args) {
        List<String> nameList = Arrays.asList("Ram", "Sheila", "Mukesh", "Rani", 
          "Nick", "Amy", "Desi", "Margo");
        Spliterator<String> splitStr = nameList.spliterator();
        Spliterator<String> splitStr2 = splitStr.trySplit();
        // Check if splitting actually happened, then use it
        if(splitStr2 != null){
            System.out.println("Spliterator-2");
            while(splitStr2.tryAdvance((n) -> System.out.println("name - " + n)));
        }
        // Original spliterator
        System.out.println("Original Spliterator");
        while(splitStr.tryAdvance((n) -> System.out.println("name - " + n)));
    }
        
}

Output

Spliterator-2
name - Ram
name - Sheila
name - Mukesh
name - Rani
Original Spliterator
name - Nick
name - Amy
name - Desi
name - Margo

Here you are splitting the spliterator, make sure to check that splitting actually happened by checking for null.

Here note one thing, according to Java docs -

If the original thread hands a spliterator off to another thread for processing, it is best if that handoff occurs before any elements are consumed with tryAdvance(), as certain guarantees (such as the accuracy of estimateSize() for SIZED spliterators) are only valid before traversal has begun.

So make sure you first do the splitting then only start any operation on the elements.

Referrence- https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/Spliterator.html

That's all for this topic Spliterator in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Stream API in Java 8
  2. Java Stream API Examples
  3. Primitive Type Streams in Java Stream API
  4. Collecting in Java Stream API
  5. Lambda Expressions in Java 8

You may also like -

  1. Method reference in Java 8
  2. interface static methods in Java 8
  3. Deadlock in Java multi-threading
  4. CyclicBarrier in Java concurrency
  5. CopyOnWriteArrayList in Java
  6. Treemap in Java
  7. Difference between Comparable and Comparator
  8. Exception Propagation in Java Exception Handling

Tuesday, 23 April 2019

Java Stream flatMap() Method

flatMap() in Java brings two features; map operations in Java stream API and flattening a nested structure together.

In mapping operation in Java stream the given function is applied to all the elements of the stream. Where as flattening a structure, in simple terms, means bringing all the nested structures at the same level. If you have a data structure with many nested levels flattening will break all the nested levels and bring all the elements at the same level.

As example if you have a list of Strings, list<String> like - [[“a”, “b”, “c”], [“c”, “d”], [“c”, “e”, “f”]] then flattening it will bring everything to the same level and the structure you will have be like this-

[“a”, “b”, “c”, “c”, “d”, “c”, “e”, “f”].

Bringing both of these features (map operation and flattening a structure) together in a method flatMap() in Java means, function will be applied to all the elements of the stream and then it will be flatten to have a single level structure.

Java flatMap usage

If you have a stream of array, list or set, in Stream API operations like count, filter, map which work on the element of the streams such grouping of elements (using array or collection) will be considered as one element which may not be what you want.

With flatMap you can flatten that structure and then stream API methods will consider them as individual elements. Let's try to clarify it with an example.

Java flatMap() example

Let’s say there is a class called Order which has a collection of items. Now you want the count of all the items in all the orders. You also want to display all the items with in all the orders.

Order class

public class Order {
    private String orderId;
    private List<String> items;
    public String getOrderId() {
        return orderId;
    }
    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }
    public List<String> getItems() {
        return items;
    }
    public void setItems(List<String> items) {
        this.items = items;
    }
}

Getting a stream containing all the items in all the orders

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class FlatMapDemo {

    public static void main(String[] args) {
        List<Order> orderList = getOrderList();
        System.out.println("Item count with Map " + orderList.stream().map
          (order -> order.getItems().stream()).count());
        System.out.println("Item count with FlatMap " + orderList.stream().flatMap
          (order -> order.getItems().stream()).count());
        // displaying all the items
        Stream<String> item = orderList.stream().flatMap(order -> order.getItems().stream());
        item.forEach(System.out::println);
    }
    
    private static List<Order> getOrderList(){
        List<Order> orderList = new ArrayList<Order>();
        Order order = new Order();
        order.setOrderId("1");
        order.setItems(Arrays.asList("Item1", "Item2", "Item3"));
        orderList.add(order);
        order = new Order();
        order.setOrderId("2");
        order.setItems(Arrays.asList("Item3", "Item5"));
        orderList.add(order);
        return orderList;
    }
}

Output

Item count with Map 2
Item count with FlatMap 5
Item1
Item2
Item3
Item3
Item5

Here you can see when you try to get the count using map() method, each item list is considered as one element so the count is displayed as 2. When you flatten the lists using flatMap() method then only you get the correct count of all the items in all the orders. Using flatMap() you are also getting all the items which are stored as a list inside orders.

flatMap Methods for primitive data types

In Java stream API there are variants of flatMap method which work with primitive data types. These methods are-

  • flatMapToInt()- Works with int data type. Returns a new IntStream.
  • flatMapToLong()- Works with long data type. Returns a new LongStream.
  • flatMapToDouble()- Works with double data type. Returns a new DoubleStream.

flatMapToInt example

If you have 2D array and you want to flatten it and get a new IntStream you can get it like this -

int[][] numArray = {{1, 2}, {3, 4}, {5, 6}};
Stream<int[]> numStream = Stream.of(numArray);
IntStream iStream = Stream.of(numArray).flatMapToInt(n -> Arrays.stream(n));
iStream.forEach(System.out::println);

Output

1
2
3
4
5
6

In the lambda expression n -> Arrays.stream(n), n denotes one of the array with in the 2D array, so first time {1,2} will be passed as the mapped stream and its contents will be placed in the new IntStream, next time another array {3,4} will be passed and so on.

That's all for this topic Java Stream flatMap() Method. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Stream API Examples
  2. Collecting in Java Stream API
  3. Spliterator in Java
  4. Primitive Type Streams in Java Stream API
  5. Java Stream API Interview Questions

You may also like -

  1. Method Reference in Java
  2. Functional Interface Annotation in Java
  3. interface default methods in Java 8
  4. Difference between ReentrantLock and Synchronized
  5. Callable and Future in Java concurrency
  6. ListIterator in Java
  7. EnumSet in Java
  8. String and thread-safety in Java