Replace loop with IntStream.range(start, number);


before java 8 if we want to find that a number is prime or not, definitely we have to go through loop given example below

private static boolean isPrime(int number) {
if(number < 2) return false;
for(int i=2; i<number; i++){
if(number % i == 0) return false;
return true;


but after java 8 it is as simple as

private static boolean isPrime(int number) {
return number > 1
&& IntStream.range(2, number).noneMatch(
index -> number % index == 0);

IntStream range method go through the range and it and it’s noneMatch method takes a Predicate  and returns true if our condition is satisfied

How to sort list using stream


As we all know that if we have to sort a list than we have to use Collections.sort(list)

but while we are using java 8 not necessary to go to Collections class while we have to sort Integer or String or like all other wrapper classes

It is as simple given below

List<Integer> list = new ArrayList<>();

System.out.println(“before list:” + list);;

just a simple sorted method  in stream api

How to make List read-only

Sometimes we need that no element should be added or deleted from our collections.

Then we should follow this stratigity

List<String> list=new ArrayList<>();


list = Collections.unmodifiableList(list);

simillary for set and map


map = Collections.unmodifiableMap(map);

And remember  if you try to add element  this will not give compiler error but java.lang.UnsupportedOperationException

Be aware while using single code(‘)

Hello all of us know that single code(‘) is used when we have to work  with character for  example like print it on console but have you ever tried to concat two chars with plus(+)


when we will test it there will be desired output


but what happen when we concat this two character using + sign
System.out.print(‘H’+ ‘a’);

The output is below

So be aware while using character 

Double Curley Braces {{ the hidden functionality

If we have to create a set or list so we have to code like this

List<String> list=new ArrayList<String>();

list.add(“a”); list.add(“b”);

But there is feature in java that we don’t have to use variable again and again,below is the example

List<String> list = new ArrayList<String>() {{

One more way that can terminate our app

All of us know about heap and stack where our objects and local variable gets memory, but one more thing we need to know that they can terminate our program abnormally

If the heap and stack collide then  the program will terminate

because stack grows toward the heap when a method is invoked and shrinks when the
method returns

Which may be  called as OutOfMemoryError