Thursday, April 22, 2021

Major Sources of JAVA SE 8: java.util & java.lang etc.

http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/function










In general:

Guide to Stream.reduce()

Reduction (The Java Tutorials > Collections > Aggregate Operations)

REMINDER: substring - ending index is exclusive! => "S".equals("String".substring(0,1))

REMINDER: substring - ending index is exclusive! => "S".equals("String".substring(0,1))


"north".substring(0,1) => "n"
"north".substring(1,2) => "o"
"north".substring(1,3) => "or"
 "hamburger".substring(4, 8) returns "urge"
 "smiles".substring(1, 5) returns "mile"

Signature:
public String substring(int startIndex)  
and  
public String substring(int startIndex, int endIndex)  
If you don't specify endIndex, java substring() method will return all the characters from startIndex.


BiFunction (Java Platform SE 8 )

compose() and andThen() methods in java.util.function.Function (Java Platform SE 8 )

Source:
https://docs.oracle.com/javase/8/docs/api/java/util/function/Function.html#compose-java.util.function.Function-


  • apply

    R apply(T t)
    Applies this function to the given argument.
    Parameters:
    t - the function argument
    Returns:
    the function result
  • compose

    default <V> Function<V,R> compose(Function<? super V,? extends T> before)
    Returns a composed function that first applies the before function to its input, and then applies this function to the result. If evaluation of either function throws an exception, it is relayed to the caller of the composed function.
    Type Parameters:
    V - the type of input to the before function, and to the composed function
    Parameters:
    before - the function to apply before this function is applied
    Returns:
    a composed function that first applies the before function and then applies this function
    Throws:
    NullPointerException - if before is null
    See Also:
    andThen(Function)
  • andThen

    default <V> Function<T,V> andThen(Function<? super R,? extends V> after)
    Returns a composed function that first applies this function to its input, and then applies the after function to the result. If evaluation of either function throws an exception, it is relayed to the caller of the composed function.
    Type Parameters:
    V - the type of output of the after function, and of the composed function
    Parameters:
    after - the function to apply after this function is applied
    Returns:
    a composed function that first applies this function and then applies the after function
    Throws:
    NullPointerException - if after is null
    See Also:
    compose(Function)

Wednesday, April 21, 2021

Modern JAVA: What is the difference between intermediate and terminal operations?

Source:

"A Stream supports several operations and these operations are divided into intermediate and terminal operations.

The distinction between this operations is that an intermediate operation is lazy while a terminal operation is not. When you invoke an intermediate operation on a stream, the operation is not executed immediately. It is executed only when a terminal operation is invoked on that stream. In a way, an intermediate operation is memorized and is recalled as soon as a terminal operation is invoked. You can chain multiple intermediate operations and none of them will do anything until you invoke a terminal operation. At that time, all of the intermediate operations that you invoked earlier will be invoked along with the terminal operation.

All intermediate operations return Stream (can be chained), while terminal operations don't. 


Intermediate Operations are:

filter(Predicate<T>)  map(Function<T>)  flatMap(Function<T>)  sorted(Comparator<T>)  peek(Consumer<T>)  distinct()  limit(long n)  skip(long n)  

Terminal operations produces a non-stream (cannot be chained) result such as primitive value, a collection or no value at all.

Terminal Operations are:

forEach  forEachOrdered  toArray  reduce  collect  min  max  count  anyMatch  allMatch  noneMatch  findFirst      findAny  

Last 5 are short-circuiting terminal operations"


Java: static final methods and their usage

Source:

LAMBA and Interfaces in modern Java - References to different methods...

Source:
https://bulldogjob.pl/news/1361-interfejsy-w-javie-referencje-metod

"referencje do metod pozwalają odwoływać się do metod bez ich wykonywania. Możliwość ta jest związana z wyrażeniami lambda, gdyż także wymaga kontekstu typu docelowego będącego interfejsem funkcyjnym. W momencie przetwarzania także referencja do metody tworzy instancję interfejsu funkcyjnego. 

Dostępnych jest kilka różnych rodzajów referencji do metod"

"* referencje do metod statycznych
* referencje do metod instancyjnych
* referencje do metod a typy sparametryzowane
* a także referencje do konstruktorów."

"Składnia używana do do tworzenia referencji do metod statycznych wygląda tak:" 
NazwaKlasy::nazwaMetody

Tuesday, April 20, 2021

Functional interface in Java SE 8+ = an interface with 1 abstract method (not derived from Object class)

Sources:



Functional interface in Java SE 8+ = an interface with 1 abstract method (not derived from Object class). 
Abstract method means with no body and not implemented.
We can also tell the compiler to treat it as a @FunctionalInterface with this annotation.

Default methods of such interfaces (with "default" keyword) are implemented with body here, and are not abstract since Java SE 8.

Java SE 8+ STREAM: peek() vs. forEach() etc.


Sources:


https://programuj.pl/blog/java8-strumienie-cz3-peek-map-collect


<R,A> Rcollect(Collector<? super T,A,R> collector)
Performs a mutable reduction operation on the elements of this stream using a Collector.
<R> Rcollect(Supplier<R> supplier, BiConsumer<R,? super T> accumulator, BiConsumer<R,R> combiner)
Performs a mutable reduction operation on the elements of this stream.


Stream<T>filter(Predicate<? super T> predicate)
Returns a stream consisting of the elements of this stream that match the given predicate.

static <T> Stream<T>generate(Supplier<T> s)
Returns an infinite sequential unordered stream where each element is generated by the provided Supplier.
static <T> Stream<T>iterate(T seed, UnaryOperator<T> f)
Returns an infinite sequential ordered Stream produced by iterative application of a function f to an initial element seed, producing a Stream consisting of seedf(seed)f(f(seed)), etc.
Stream<T>limit(long maxSize)
Returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length.
<R> Stream<R>map(Function<? super T,? extends R> mapper)
Returns a stream consisting of the results of applying the given function to the elements of this stream.

static <T> Stream<T>of(T... values)
Returns a sequential ordered stream whose elements are the specified values.
static <T> Stream<T>of(T t)
Returns a sequential Stream containing a single element.


Optional<T>reduce(BinaryOperator<T> accumulator)
Performs a reduction on the elements of this stream, using an associative accumulation function, and returns an Optional describing the reduced value, if any.
Treduce(T identity, BinaryOperator<T> accumulator)
Performs a reduction on the elements of this stream, using the provided identity value and an associative accumulation function, and returns the reduced value.
<U> Ureduce(U identity, BiFunction<U,? super T,U> accumulator, BinaryOperator<U> combiner)
Performs a reduction on the elements of this stream, using the provided identity, accumulation and combining functions.


<R> Stream<R>flatMap(Function<? super T,? extends Stream<? extends R>> mapper)
Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.

voidforEach(Consumer<? super T> action)
Performs an action for each element of this stream.

Stream<T>peek(Consumer<? super T> action)
Returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream.



Monday, April 19, 2021

ThreadLocal (Java Platform SE 7 ) and AtomicInteger...

Source:

import java.util.concurrent.atomic.AtomicInteger;  
import java.lang.ThreadLocal<T>;
   public class ThreadId {       // Atomic integer containing the next thread ID to be assigned       private static final AtomicInteger nextId = new AtomicInteger(0);         // Thread local variable containing each thread's ID       private static final ThreadLocal<Integer> threadId =           new ThreadLocal<Integer>() {               @Override protected Integer initialValue() {                   return nextId.getAndIncrement();           }       };         // Returns the current thread's unique ID, assigning it if necessary       public static int get() {           return threadId.get();       }   }

StringUtils (Apache Commons Lang 3.12.0 API)

Sunday, April 18, 2021

Java Stream flatMap(). HOW-TO

Source:
https://howtodoinjava.com/java8/stream-flatmap-example/#:~:text=flatMap()%20is%20an%20intermediate,mapping%20function%20to%20each%20element

flatMap() - sample of flattening:

Flattening example 1
Before flattening   : [[1, 2, 3], [4, 5], [6, 7, 8]]
After flattening    : [1, 2, 3, 4, 5, 6, 7, 8]


Flattening example 2
Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8);
Stream<String> words = lines.flatMap(line -> Stream.of(line.split(" +")));


Similar flatMap() Methods
IntStream flatMapToInt(Function<? super T,? extends IntStream> mapper)
LongStream flatMapToLong(Function<? super T,? extends LongStream> mapper)
DoubleStream flatMapToDouble(Function<? super T,? extends DoubleStream> mapper)