Java 8

Manupuri NithinManupuri Nithin
7 min read
  • Functional Interface:

    functional interface is an interface that has exactly one abstract method.

  •                             #Single Abstract methods
                                   Runnable() ->run();
                                   Callable() -> call();
                                   Comparator()->compare(T o1, T o2);
                                   ActionListener()->actionPerformed(ActionEvent e)
    
  • Lambda expressions:

    Lambda expressions are used to implement the functional interface programming and concise the code to represent anonymous function.

    anonymous function: it has no return type, no method name and no

  • Default Methods and Static methods in Interface:

    Default Methods:

  • Predefined Methods:

    Take some input and perform some conditional check and returns Boolean value--->predicate.

    •                                                 import java.util.function.Predicate;
      
                                                        Predicate<Integer> p=(b)->b%2==0;
                                                          boolean b=p.test(5);
      

                                        **Function**: take some input and perform some operation and return result which need not be Boolean type.




* ```java

                                Function<String,Integer> f=x-> x.length();
                                int a=f.apply("Hello");
  • accept some input and perform required operation and not required to be return anything-->consumer, it has uses accept.

    • 
                                                        Consumer<Integer> consumer=c->{
                                                              int i=0;
                                                              for(i=1;i<c;i++){
                                                                  i*=i;
                                                              }
                                                              System.out.println(i);
                                                          };
                                                          consumer.accept(2);
      





* **Supplier**: It will not take any input it returns Object.

* ```java
                        interface supplier<R>
                        {
                        public R get();
                        }

                        Supplier<Date> s=()->new Date();

                         s.get();
  • Method References:

  • Stream Api:

    what is stream?

    It used for processing the collection objects.

    we can create stream by using Stream() in java.util.stream package.

  • BaseStream<T> is the super interface in java.util.stream and it has extends IntStream, LongStream, DoubleStream,Stream<T>

  • 
                     BaseStream common Method which are applicable for all the streams
    
                  Iterator  iterator() -> it uses for legacy classe to iterate it has next(),hasNext() methods
                  SplitIterator<T> splitIterator() -> it used to spltit the stream into parat whoch enables the parallel processing it uses trySplit(),and  uses forEachRemaning() method
                  boolean isParallel() -> to check the stream is parallel processing
                  Sequential() -> it used for convert the stream into the sequential processing
                  parallel() -> it uses  to cconvert the stream into the parallel processing
                  onClose(Runnable r)-> it call when the stream is closing befor it call back this
                  close() -> which is used to close the resources
                  unordered() -> it uses to have unordered processing when we use parall processing  their it uses ordered when we give this it prrint the unordered data
    

    Stream<T>:

  • It extends from the BaseStream<T>.

    Methods that are present int the Stream are listed below.

  •             Stream<T> filter(Predicate<? super T> predicate) -> it return new stream that passes from the filter
                <R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R>> mapper) ->  it maps the stream or modify the vale and pass value as a stream
                IntStream mapToInt(ToIntFunction<? super T> mapper) -> it takes the input  and pass as a new stream whoch convert the all input values into the Integer
                LongStream mapToLong(ToLongFunction<? super T> mapper) -> it takes the innput as appas as new stream before it convert inot the Long
                DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper) -> it takes the innput as appas as new stream before it convert inot the double
                <R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R>> mapper)  -> it takes the list of streams it iterate the list of stream only it iterates one time 
                IntStream flatMapToInt(Function<? super T,? extends IntStream> mapper)
                LongStream flatMapToLong(Function<? super T,? extends LongStream> mapper)
                DoubleStream flatMapToDouble(Function<? super T,? extends DoubleStream> mapper)
    
                Stream<T> distinct() -> eturns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream and it is stateful
              Stream<T> sorted() ->Returns a stream consisting of the elements of this stream, sorted according to natural order. If the elements of this stream are not Comparable, a java.lang.ClassCastException may be thrown when the terminal operation is executed.
              Stream<T> sorted(Comparator<? super T> comparator) -> Returns a stream consisting of the elements of this stream, sorted according to the provided Comparator.
              Stream<T> peek(Consumer<? super T> action) -> it returns a new stream 
              Stream<T> limit(long maxSize) ->  Returns: the new stream ,throws:IllegalArgumentException - if maxSize is negative
              Stream<T> skip(long n) ->Returns a stream consisting of the remaining elements of this stream after discarding the first n elements of the stream. If this stream contains fewer than n elements then an empty stream will be returned.
              void forEach(Consumer) ->  it is terminal operation
            void forEachOrdered(Consumer<? super T> action) -> It makes sure the  corect order if we use parallel stream no order
            Object[] toArray()-> it is termianl Returns an array containing the elements of this stream.
    
            <A> A[] toArray(IntFunction<A[]> generator) -> terminal operation similar to toArray() but it has more control about the return type we should method th eretrun type as functuion to pass in toArray method
            T reduce(T identity, BinaryOperator<T> accumulator)
            Optional<T> reduce(BinaryOperator<T> accumulator)
            long count() ->Returns the count of elements in this stream. 
            Optional<T> min(Comparator<? super T> comparator)
            Returns the minimum element of this stream according to the provided Comparator. This is a special case of a reduction.
            This is a terminal operation.
            Optional<T> max(Comparator<? super T> comparator)
            Returns the maximum element of this stream according to the provided Comparator. This is a special case of a reduction.
            This is a terminal operation.
    
            <R> R collect(Supplier<R> supplier,
                          BiConsumer<R,? super T> accumulator,
                          BiConsumer<R,R> combiner)
    
            <R,A> R collect(Collector<? super T,A,R> collector)
         boxed()  ->In Java, the boxed() method is used to convert a stream of primitive types (like int, double, long) into a stream of their corresponding wrapper classes (Integer, Double, Long).
    
  • Collector class:

    In Java 8, the Collectors class in the java.util.stream package provides a set of useful static methods to perform reduction operations on streams and transform them into collections. These operations include methods like groupingBy(), partitioningBy() ,joining(), toSet(), toList(), toMap().

    Concurrency Enhancements:

    • parallel Streams ():

      Java 8 introduced Streams as part of the java.util.stream package, and one of the most notable concurrency enhancements is the ability to process streams in parallel. By using parallel streams, Java automatically splits the stream into multiple sub-streams, processes them concurrently using ForkJoinPool, and then merges the results.

    • CompletableFuture :

      In java.util.Concurrent package this completable Future were introduced

      Non-blocking: CompletableFuture allows non-blocking asynchronous programming.

      Chaining: You can chain multiple operations to run one after another using methods like thenApply(), thenAccept(), etc.

      Combining futures: Combine multiple asynchronous tasks with thenCombine(), thenCompose(), or allOf().

      • thenCombine is used to combine two independent CompletableFutures.

        • thenAccept is used to consume a result without returning anything.

        • thenCompose is used for dependent async tasks that need to be chained sequentially.

        • thenApply is used to transform a CompletableFuture’s result, producing a new CompletableFuture with the transformed result.

runAsync(Runnable r) → which not return Completable Stage

  • supplyAsync(Runnable r) → which will return Completable Stage

  • Atomic and ConcurrentMap Enhancements

  • Java 8 improved the atomic classes (like AtomicInteger, AtomicLong, AtomicReference, etc.) and added enhancements to ConcurrentMap.

    New Methods in ConcurrentMap:

    Java 8 introduced new atomic methods in ConcurrentMap like:

    • putIfAbsent(): Puts the value in the map if the key is not already present.

    • computeIfAbsent() and computeIfPresent(): Compute values lazily if a key is absent or present in the map.

    • merge(): Combines the existing value with a new value for a given key.

StampedLock

Java 8 introduced StampedLock, which is an advanced lock mechanism that improves on traditional read-write locks (like ReentrantReadWriteLock). It allows optimistic locking to reduce contention and increase throughput in highly concurrent scenarios.

Key Features:

  • Optimistic Locking: The StampedLock allows optimistic reads, which don’t block, and the lock can later validate if it was successful in reading without contention.

  • Stamped Tokens: Instead of holding a simple lock, StampedLock returns a stamp (token) that can be used to release or upgrade the lock.

Duration:

This class introduced in Java 8 as part of the java.time package (specifically under java.time.Duration). It is used to represent a quantity of time and The Duration class is designed to model the difference between two points in time and is particularly useful when you're dealing with time-based calculations.

There are some methods in this class that are :

1. Factory Methods: ou can create a Duration object using static methods like ofSeconds(), ofMinutes(), ofHours(), ofDays(), etc.

2.Difference between the times : You can create a Duration between two Temporal objects like Instant or LocalTime.

Instant start = Instant.now();

Instant end = Instant.now();

Duration duration = Duration.between(start, end);

Common Operations on a Duration:

  • Getting Time Components: You can extract the time components like seconds, minutes, and hours from a Duration.

      long seconds = duration.getSeconds();
      long nano = duration.getNano();
    
  • Addition and Subtraction: You can add or subtract time from a Duration.

      javaCopy codeDuration added = duration.plusMinutes(5);   // Add 5 minutes
      Duration subtracted = duration.minusHours(1); // Subtract 1 hour
    
  • Comparing Durations: You can compare two Duration objects using compareTo() or equals().

      javaCopy codeif (duration1.compareTo(duration2) > 0) {
          System.out.println("Duration1 is longer");
      }
    
0
Subscribe to my newsletter

Read articles from Manupuri Nithin directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Manupuri Nithin
Manupuri Nithin