Java 8 features

Java 8 features

Hello everyone today i am sharing about Java 8 Some features that can improve our productivity and reduce our execution time

1. Lambda expressions

2. ForEach() method

3. Method references

4. Functional interfaces

5. Stream API

6. Optional class

7. Parallel sort

8. Date and Time

  1. Lambda Expressions :

Lambda expression helps us to write our code in a functional style. It provides a clear way a help using an expression.

It is very useful in a collection library in which it helps to iterate, filter and extract data.

Example:

public class LambdaExprEx{  
    public static void main(String[] args) {  

        List<String> list=new ArrayList<String>();  
        list.add("Rajashekar");  
        list.add("Chinnu");  
        list.add("Rohit");  
        list.add("Hello");  
        list.add("Java");
        list.forEach((n)->System.out.println(n));  
    }  
}
OUTPUT :-
 Rajashekar 
 Chinnu
 Rohit  
 Hello
 Java

Example 2:


public static void main(String[] args) {
        // TODO Auto-generated method stub
        InterfaceA a1=()-> System.out.println("m1 method");
        a1.m1();

        InterfaceB b1=(a,b,c)->
        {
            System.out.println(a+b+c);
        };
        b1.m2(10,20,30);

        InterfaceC c1=(int a,int b)->
        {
            if(a<b)
            {
                return a;
            }
            else
            {
                return b;
            }
        };
        int min=c1.m3(100,200);
        System.out.println("Minimum"+min);

        InterfaceD d1=(int a,int b)->
        {
            for(int i=a;i<=b;i++)
            {
                System.out.println(i);
            }
        };
        d1.m4(1,10);

    }

}
public interface InterfaceD {
    void m4(int a,int b);

}
public interface InterfaceC {
    int m3(int a,int b);

}
public interface InterfaceB {
    void m2(int a,int b,int c);
}
public interface InterfaceA {
    void m1();

}

output:

m1 method
60
Minimum100
1
2
3
4
5
6
7
8
9
10
  1. ForEach() method : -

Java provides a new method forEach() to iterate the elements. It is defined in the Iterable and Stream interface.

public class ForEachExample {  
    public static void main(String[] args) {  
        List<String>  list= new ArrayList<String>();  
        list.add("ABC");  
        list.add("XYZ");  
        list.add("Java");  
        list.add("Hello");  
        list.add("World"); 
        System.out.println("------------Iterating by passing method reference---------------");  
        list.forEach(System.out::println);  
    }  
}
output:-
------------Iterating by passing method reference---------------


 ABC 
 XYZ
 Java  
 Hello
 World
  1. Java SteamAPI: -

    it used to perform operations on streams and manipulate the data .it take input from collection frame classes. it won't store any data.

consumervoid accept(T t)accepts one argumentit won't return anything
predicateboolean test(T t)accepts one argumenttrue or false
functionR apply(T t)accepts one argumentreturn some value
supplierT get()zeroreturns some value
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
public class ClassStreamAPI 
{
   public static void main(String[] args) 
   {
      Stream<String> s1=Stream.empty();

      List<Integer> l1=Arrays.asList(1,2,3,4,5);
      Stream<Integer> s2=l1.stream();
      s2.forEach(ele->System.out.println(ele));
      System.out.println("========================");

      l1.stream().filter(x->x%2==0).forEach(ele->System.out.println(ele));

      System.out.println("========================");
      l1.stream().filter(x->x%2!=0).map(x->x*10).forEach(ele->System.out.println(ele));

      System.out.println("========================");

      List<Integer> l2=Arrays.asList(5,2,2,1,2,6,3,6,4,5);
      Stream<Integer> s3=l2.stream();

      s3.distinct().sorted().forEach(ele->System.out.println(ele));
      System.out.println("========================");

      l2.stream().distinct().sorted(Comparator.reverseOrder()).forEach(ele->System.out.println(ele));

      System.out.println("========================");

      long c=l2.stream().distinct().count();
      System.out.println(c);
      System.out.println("========================");

      boolean b=l2.stream().allMatch(x->x>1);
      System.out.println(b);
      System.out.println("========================");

      boolean b1=l2.stream().anyMatch(x->x>3);
      System.out.println(b1);
      System.out.println("========================");

      boolean b2=l2.stream().noneMatch(x->x>1);
      System.out.println(b2);

      int sum= l1.stream().reduce(0,(p,q)->p+q); 

     System.out.println(sum); 
   }
}

output:

1
2
3
4
5
=======================================
2
4
========================================
10
30
50
========================================
1
2
3
4
5
6
========================================
6
5
4
3
2
1
========================================
6
========================================
false
========================================
true
========================================
true
========================================
false
========================================
15

Date/Time API:-

Java has introduced a new Date and Time API since Java 8. The java.time package contains Java 8 Date and Time classes.


import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Arrays;

public class ClassDate {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        System.out.println(ZonedDateTime.now());
        System.out.println(ZoneId.getAvailableZoneIds());
        System.out.println(LocalTime.now(ZoneId.of("America/Los_Angeles")));
        System.out.println(LocalTime.now(ZoneId.of("America/New_York")));
        System.out.println(LocalTime.now(ZoneId.of("Asia/Kolkata")));

    }

}

output:

2023-10-04T13:29:12.504+05:30[Asia/Calcutta]
[Asia/Aden, America/Cuiaba, Etc/GMT+9, Etc/GMT+8, Africa/Nairobi, America/Marigot, Asia/Aqtau, Pacific/Kwajalein, America/El_Salvador, Asia/Pontianak, Africa/Cairo, Pacific/Pago_Pago, Africa/Mbabane, Asia/Kuching, Pacific/Honolulu, Pacific/Rarotonga, America/Guatemala, Australia/Hobart, Europe/London, America/Belize, America/Panama, Asia/Chungking, America/Managua, America/Indiana/Petersburg, Asia/Yerevan, Europe/Brussels, GMT, Europe/Warsaw, America/Chicago, Asia/Kashgar, Chile/Continental, Pacific/Yap, CET, Etc/GMT-1, Etc/GMT-0, Europe/Jersey, America/Tegucigalpa, Etc/GMT-5, Europe/Istanbul, America/Eirunepe, Etc/GMT-4, America/Miquelon, Etc/GMT-3, Europe/Luxembourg, Etc/GMT-2, Etc/GMT-9, America/Argentina/Catamarca, Etc/GMT-8, Etc/GMT-7, Etc/GMT-6, Europe/Zaporozhye, Canada/Yukon, Canada/Atlantic, Atlantic/St_Helena, Australia/Tasmania, Libya, Europe/Guernsey, America/Grand_Turk, US/Pacific-New, Asia/Samarkand, America/Argentina/Cordoba, Asia/Phnom_Penh, Africa/Kigali, Asia/Almaty, US/Alaska, Asia/Dubai, Europe/Isle_of_Man, America/Araguaina, Cuba, Asia/Novosibirsk, America/Argentina/Salta, Etc/GMT+3, Africa/Tunis, Etc/GMT+2, Etc/GMT+1, Pacific/Fakaofo, Africa/Tripoli, Etc/GMT+0, Israel, Africa/Banjul, Etc/GMT+7, Indian/Comoro, Etc/GMT+6, Etc/GMT+5, Etc/GMT+4, Pacific/Port_Moresby, US/Arizona, Antarctica/Syowa, Indian/Reunion, Pacific/Palau, Europe/Kaliningrad, America/Montevideo, Africa/Windhoek, Asia/Karachi, Africa/Mogadishu, Australia/Perth, Brazil/East, Etc/GMT, Asia/Chita, Pacific/Easter, Antarctica/Davis, Antarctica/McMurdo, Asia/Macao, America/Manaus, Africa/Freetown, Europe/Bucharest, America/Argentina/Mendoza, Asia/Macau, Europe/Malta, Mexico/BajaSur, Pacific/Tahiti, Africa/Asmera, Europe/Busingen, America/Argentina/Rio_Gallegos, Africa/Malabo, Europe/Skopje, America/Catamarca, America/Godthab, Europe/Sarajevo, Australia/ACT, GB-Eire, Africa/Lagos, America/Cordoba, Europe/Rome, Asia/Dacca, Indian/Mauritius, Pacific/Samoa, America/Regina, America/Fort_Wayne, America/Dawson_Creek, Africa/Algiers, Europe/Mariehamn, America/St_Johns, America/St_Thomas, Europe/Zurich, America/Anguilla, Asia/Dili, America/Denver, Africa/Bamako, GB, Mexico/General, Pacific/Wallis, Europe/Gibraltar, Africa/Conakry, Africa/Lubumbashi, Asia/Istanbul, America/Havana, NZ-CHAT, Asia/Choibalsan, America/Porto_Acre, Asia/Omsk, Europe/Vaduz, US/Michigan, Asia/Dhaka, America/Barbados, Europe/Tiraspol, Atlantic/Cape_Verde, Asia/Yekaterinburg, America/Louisville, Pacific/Johnston, Pacific/Chatham, Europe/Ljubljana, America/Sao_Paulo, Asia/Jayapura, America/Curacao, Asia/Dushanbe, America/Guyana, America/Guayaquil, America/Martinique, Portugal, Europe/Berlin, Europe/Moscow, Europe/Chisinau, America/Puerto_Rico, America/Rankin_Inlet, Pacific/Ponape, Europe/Stockholm, Europe/Budapest, America/Argentina/Jujuy, Australia/Eucla, Asia/Shanghai, Universal, Europe/Zagreb, America/Port_of_Spain, Europe/Helsinki, Asia/Beirut, Asia/Tel_Aviv, Pacific/Bougainville, US/Central, Africa/Sao_Tome, Indian/Chagos, America/Cayenne, Asia/Yakutsk, Pacific/Galapagos, Australia/North, Europe/Paris, Africa/Ndjamena, Pacific/Fiji, America/Rainy_River, Indian/Maldives, Australia/Yancowinna, SystemV/AST4, Asia/Oral, America/Yellowknife, Pacific/Enderbury, America/Juneau, Australia/Victoria, America/Indiana/Vevay, Asia/Tashkent, Asia/Jakarta, Africa/Ceuta, America/Recife, America/Buenos_Aires, America/Noronha, America/Swift_Current, Australia/Adelaide, America/Metlakatla, Africa/Djibouti, America/Paramaribo, Europe/Simferopol, Europe/Sofia, Africa/Nouakchott, Europe/Prague, America/Indiana/Vincennes, Antarctica/Mawson, America/Kralendijk, Antarctica/Troll, Europe/Samara, Indian/Christmas, America/Antigua, Pacific/Gambier, America/Indianapolis, America/Inuvik, America/Iqaluit, Pacific/Funafuti, UTC, Antarctica/Macquarie, Canada/Pacific, America/Moncton, Africa/Gaborone, Pacific/Chuuk, Asia/Pyongyang, America/St_Vincent, Asia/Gaza, Etc/Universal, PST8PDT, Atlantic/Faeroe, Asia/Qyzylorda, Canada/Newfoundland, America/Kentucky/Louisville, America/Yakutat, Asia/Ho_Chi_Minh, Antarctica/Casey, Europe/Copenhagen, Africa/Asmara, Atlantic/Azores, Europe/Vienna, ROK, Pacific/Pitcairn, America/Mazatlan, Australia/Queensland, Pacific/Nauru, Europe/Tirane, Asia/Kolkata, SystemV/MST7, Australia/Canberra, MET, Australia/Broken_Hill, Europe/Riga, America/Dominica, Africa/Abidjan, America/Mendoza, America/Santarem, Kwajalein, America/Asuncion, Asia/Ulan_Bator, NZ, America/Boise, Australia/Currie, EST5EDT, Pacific/Guam, Pacific/Wake, Atlantic/Bermuda, America/Costa_Rica, America/Dawson, Asia/Chongqing, Eire, Europe/Amsterdam, America/Indiana/Knox, America/North_Dakota/Beulah, Africa/Accra, Atlantic/Faroe, Mexico/BajaNorte, America/Maceio, Etc/UCT, Pacific/Apia, GMT0, America/Atka, Pacific/Niue, Canada/East-Saskatchewan, Australia/Lord_Howe, Europe/Dublin, Pacific/Truk, MST7MDT, America/Monterrey, America/Nassau, America/Jamaica, Asia/Bishkek, America/Atikokan, Atlantic/Stanley, Australia/NSW, US/Hawaii, SystemV/CST6, Indian/Mahe, Asia/Aqtobe, America/Sitka, Asia/Vladivostok, Africa/Libreville, Africa/Maputo, Zulu, America/Kentucky/Monticello, Africa/El_Aaiun, Africa/Ouagadougou, America/Coral_Harbour, Pacific/Marquesas, Brazil/West, America/Aruba, America/North_Dakota/Center, America/Cayman, Asia/Ulaanbaatar, Asia/Baghdad, Europe/San_Marino, America/Indiana/Tell_City, America/Tijuana, Pacific/Saipan, SystemV/YST9, Africa/Douala, America/Chihuahua, America/Ojinaga, Asia/Hovd, America/Anchorage, Chile/EasterIsland, America/Halifax, Antarctica/Rothera, America/Indiana/Indianapolis, US/Mountain, Asia/Damascus, America/Argentina/San_Luis, America/Santiago, Asia/Baku, America/Argentina/Ushuaia, Atlantic/Reykjavik, Africa/Brazzaville, Africa/Porto-Novo, America/La_Paz, Antarctica/DumontDUrville, Asia/Taipei, Antarctica/South_Pole, Asia/Manila, Asia/Bangkok, Africa/Dar_es_Salaam, Poland, Atlantic/Madeira, Antarctica/Palmer, America/Thunder_Bay, Africa/Addis_Ababa, Europe/Uzhgorod, Brazil/DeNoronha, Asia/Ashkhabad, Etc/Zulu, America/Indiana/Marengo, America/Creston, America/Mexico_City, Antarctica/Vostok, Asia/Jerusalem, Europe/Andorra, US/Samoa, PRC, Asia/Vientiane, Pacific/Kiritimati, America/Matamoros, America/Blanc-Sablon, Asia/Riyadh, Iceland, Pacific/Pohnpei, Asia/Ujung_Pandang, Atlantic/South_Georgia, Europe/Lisbon, Asia/Harbin, Europe/Oslo, Asia/Novokuznetsk, CST6CDT, Atlantic/Canary, America/Knox_IN, Asia/Kuwait, SystemV/HST10, Pacific/Efate, Africa/Lome, America/Bogota, America/Menominee, America/Adak, Pacific/Norfolk, America/Resolute, Pacific/Tarawa, Africa/Kampala, Asia/Krasnoyarsk, Greenwich, SystemV/EST5, America/Edmonton, Europe/Podgorica, Australia/South, Canada/Central, Africa/Bujumbura, America/Santo_Domingo, US/Eastern, Europe/Minsk, Pacific/Auckland, Africa/Casablanca, America/Glace_Bay, Canada/Eastern, Asia/Qatar, Europe/Kiev, Singapore, Asia/Magadan, SystemV/PST8, America/Port-au-Prince, Europe/Belfast, America/St_Barthelemy, Asia/Ashgabat, Africa/Luanda, America/Nipigon, Atlantic/Jan_Mayen, Brazil/Acre, Asia/Muscat, Asia/Bahrain, Europe/Vilnius, America/Fortaleza, Etc/GMT0, US/East-Indiana, America/Hermosillo, America/Cancun, Africa/Maseru, Pacific/Kosrae, Africa/Kinshasa, Asia/Kathmandu, Asia/Seoul, Australia/Sydney, America/Lima, Australia/LHI, America/St_Lucia, Europe/Madrid, America/Bahia_Banderas, America/Montserrat, Asia/Brunei, America/Santa_Isabel, Canada/Mountain, America/Cambridge_Bay, Asia/Colombo, Australia/West, Indian/Antananarivo, Australia/Brisbane, Indian/Mayotte, US/Indiana-Starke, Asia/Urumqi, US/Aleutian, Europe/Volgograd, America/Lower_Princes, America/Vancouver, Africa/Blantyre, America/Rio_Branco, America/Danmarkshavn, America/Detroit, America/Thule, Africa/Lusaka, Asia/Hong_Kong, Iran, America/Argentina/La_Rioja, Africa/Dakar, SystemV/CST6CDT, America/Tortola, America/Porto_Velho, Asia/Sakhalin, Etc/GMT+10, America/Scoresbysund, Asia/Kamchatka, Asia/Thimbu, Africa/Harare, Etc/GMT+12, Etc/GMT+11, Navajo, America/Nome, Europe/Tallinn, Turkey, Africa/Khartoum, Africa/Johannesburg, Africa/Bangui, Europe/Belgrade, Jamaica, Africa/Bissau, Asia/Tehran, WET, Africa/Juba, America/Campo_Grande, America/Belem, Etc/Greenwich, Asia/Saigon, America/Ensenada, Pacific/Midway, America/Jujuy, Africa/Timbuktu, America/Bahia, America/Goose_Bay, America/Virgin, America/Pangnirtung, Asia/Katmandu, America/Phoenix, Africa/Niamey, America/Whitehorse, Pacific/Noumea, Asia/Tbilisi, America/Montreal, Asia/Makassar, America/Argentina/San_Juan, Hongkong, UCT, Asia/Nicosia, America/Indiana/Winamac, SystemV/MST7MDT, America/Argentina/ComodRivadavia, America/Boa_Vista, America/Grenada, Australia/Darwin, Asia/Khandyga, Asia/Kuala_Lumpur, Asia/Thimphu, Asia/Rangoon, Europe/Bratislava, Asia/Calcutta, America/Argentina/Tucuman, Asia/Kabul, Indian/Cocos, Japan, Pacific/Tongatapu, America/New_York, Etc/GMT-12, Etc/GMT-11, Etc/GMT-10, SystemV/YST9YDT, Etc/GMT-14, Etc/GMT-13, W-SU, America/Merida, EET, America/Rosario, Canada/Saskatchewan, America/St_Kitts, Arctic/Longyearbyen, America/Fort_Nelson, America/Caracas, America/Guadeloupe, Asia/Hebron, Indian/Kerguelen, SystemV/PST8PDT, Africa/Monrovia, Asia/Ust-Nera, Egypt, Asia/Srednekolymsk, America/North_Dakota/New_Salem, Asia/Anadyr, Australia/Melbourne, Asia/Irkutsk, America/Shiprock, America/Winnipeg, Europe/Vatican, Asia/Amman, Etc/UTC, SystemV/AST4ADT, Asia/Tokyo, America/Toronto, Asia/Singapore, Australia/Lindeman, America/Los_Angeles, SystemV/EST5EDT, Pacific/Majuro, America/Argentina/Buenos_Aires, Europe/Nicosia, Pacific/Guadalcanal, Europe/Athens, US/Pacific, Europe/Monaco]
00:59:12.559
03:59:12.644
13:29:12.645

Java Parallel Array Sorting

Java provides a new additional feature in Arrays class which is used to sort array elements parallelly.

The parallelSort() method has added to java.util.Arrays class that uses the JSR 166 Fork/Join parallelism common pool to provide sorting of arrays.

It is an overloaded method.

import java.util.Arrays;

public class ClassParallelSort {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] a1={1,7,2,4,9,8,5,2};
        /*Arrays.sort(a1);
        System.out.println(Arrays.toString(a1));*/

        Arrays.parallelSort(a1,0,4);
        System.out.println(Arrays.toString(a1));
        System.out.println("==================================");

        Arrays.parallelSort(a1,3,8);
        System.out.println(Arrays.toString(a1));
        }

    }

output:-

[1, 2, 4, 7, 9, 8, 5, 2]
==================================
[1, 2, 4, 2, 5, 7, 8, 9]

Optional class

Java introduced a new class Optional in Java 8. It is a public final class which is used to deal with NullPointerException in Java application.

We must import java.util package to use this class. It provides methods to check the presence of value for particular variable.

import java.util.Optional;

public class ClassOptional {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String s=null;
        //System.out.println(s.length());

        String[] s2=new String[10];
        //System.out.println(s2[6].length());
        s2[7]="abc";

        Optional<Integer> o1=Optional.empty();
        System.out.println(o1);

        Optional<String> o2=Optional.ofNullable(s2[6]);
        System.out.println(o2);
        if(o2.isPresent())
        {
            System.out.println(s2[6].length());
        }
        else
        {
            System.out.println("empty String");
        }

    }

}

output:-

Optional.empty
Optional.empty
empty String

Functional Interface

An Interface that contains only one abstract method is known as functional interface. It can have any number of default and static methods. It can also declare methods of object class.

Functional interfaces are also known as Single Abstract Method Interfaces (SAM Interfaces).

@FunctionalInterface  
interface running{  
    void run(String msg);  
}  
public class Functional implements running{  
    public void run(String msg){  
        System.out.println(msg);  
    }  
    public static void main(String[] args) {  
        Functional f = new Functional();  
        f.run("Hi Functional interface");  
    }  
}

output:-

Hi Functional interface

Method References

Java 8 Method reference is used to refer method of functional interface . It is compact and easy form of lambda expression.

Each time when you are using lambda expression to just referring a method, you can replace your lambda expression with method reference.

@FunctionalInterface
public interface InterfaceD
{
    void meth2();
}
public class ClassMethodReference2
{
      void show()
      {
          System.out.println("Method reference- Non-static method");
      }

      static void show2()
      {
          System.out.println("Method reference- static method");
      }

      ClassMethodReference2()
      {
          System.out.println("Method reference- Constructor");
      }
}
public class ClassMethodReference
{
    void fun()
    {
           //InterfaceD p= new ClassMethodReference2()::show; //non-static method 

        //InterfaceD p=ClassMethodReference2::show2;

        InterfaceD p=ClassMethodReference2::new;

        p.meth2();


    }

   public static void main(String[] args) 
   {
       ClassMethodReference m1=new ClassMethodReference();
       m1.fun();
    }
}

output:-

method refence non static method