Sunday, April 29, 2018

Java 8 Stream 2


http://www.baeldung.com/java-stream-indices
Stream.iterate(1, i -> i <= 3, i -> i + 1)
.forEach(System.out::println);

https://www.leveluplunch.com/java/tutorials/028-reverse-order-stream-elements-java8/
    Stream.of("One", "Two", "Three", "Four")
            .collect(Collectors.toCollection(LinkedList::new))
            .descendingIterator().forEachRemaining(System.out::println);
IntStream.iterate(to - 1, i -> i - 1).limit(to - from)
Stream.of("1", "2", "20", "3")
      .collect(Collectors.toCollection(ArrayDeque::new)) // or LinkedList
      .descendingIterator()
      .forEachRemaining(System.out::println);

http://www.java2s.com/Tutorials/Java/Stream_How_to/Stream_Convert/Convert_String_to_TreeSet.htm
    Set<String> wordsSet = words.collect(Collectors.toCollection(TreeSet::new));
https://www.programcreek.com/2014/01/reduce-stream-examples/
int s = wordStream.map(s -> s.length())
  .mapToInt(Integer::new)
  .sum();
We can also use the Stream.reduce() method which is a more general method:
Stream<Integer> lengthStream = wordStream.map(s -> s.length());
Optional<Integer> sum = lengthStream.reduce((x, y) -> x + y);
Stream.reduce() take input as an accumulator function which takes two parameters: a partial result of the reduction (in this case, the sum of all processed integers so far) and the next element of the stream (in this case, an integer). It returns a new partial result. In this case, the accumulator function is a lambda expression that adds two Integer values and returns an Integer value.
Instead of using lambda expression, you can also use:
Optional<Integer> sum = lengthStream.reduce(Integer::sum);
In addition, we can also write reduce() method like the following:
int s = wordStream.reduce(0, (x, y) -> x + y.length(), (x, y) -> x + y);
System.out.println(s);
The three parameters are identify, reducer, and combiner.
- identity - identity value for the combiner function
- reducer - function for combining two results
- combiner - function for adding an additional element into a result.
https://www.geeksforgeeks.org/stream-reduce-java-examples/

T reduce(T identity, BinaryOperator<T> accumulator);

Where, identity is initial value 
of type T and accumulator is a 
function for combining two values.

        Optional<String> longestString = words.stream()
                                   .reduce((word1, word2)
                             -> word1.length() > word2.length()
                                           ? word1 : word2);
        Optional<String> String_combine = Arrays.stream(array)
                                           .reduce((str1, str2)
                                           -> str1 + "-" + str2)

        int product = IntStream.range(2, 8)
                     .reduce((num1, num2) -> num1 * num2)
                     .orElse(-1);
https://www.sitepoint.com/java-8-streams-filter-map-reduce/
A reduction operation is one which allows you to compute a result using all the elements present in a stream. Reduction operations are also called terminal operations because they are always present at the end of a chain of Streammethods. We’ve already been using a reduction method in our previous examples: the toArray method

String result = Arrays.stream(myArray)
                .reduce("", (a,b) -> a + b);
https://stackoverflow.com/questions/22577197/java-8-streams-collect-vs-reduce
<R,A> R collect(Collector<? super T,A,R> collector)

T reduce(T identity, BinaryOperator<T> accumulator)
So collect returns any R whereas reduce returns T - the type of the Stream.
reduce is a "fold" operation, it applies a binary operator to each element in the stream where the first argument to the operator is the return value of the previous application and the second argument is the current stream element.
collection is an aggregation operation where a "collection" is created and each element is "added" to that collection. Collections in different parts of the stream are then added together.

  • collect() can only work with mutable result objects.
  • reduce() is designed to work with immutable result objects.

https://www.javabrahman.com/java-8/java-8-reducing-with-streams-reduce-method-tutorial-with-examples/
    Double totalSalaryExpense = employeeList.stream()
                               .map(emp -> emp.getSalary())
                               .reduce(0.00,(a,b) -> a+b);
Optional<Employee> maxSalaryEmp=employeeList.stream()
    .reduce((Employee a, Employee b) -> a.getSalary() < b.getSalary() ? b:a);

https://www.logicbig.com/tutorials/core-java-tutorial/java-util-stream/reduction.html
       int i = IntStream.range(1, 6)
                        .reduce((a, b) -> a * b)
                        .orElse(-1);
This method has an extra 'identity' parameter.
  • Identity is the initial value of reduction:
    int i = IntStream.empty()
                     .reduce(1, (a, b) -> a * b);
http://4comprehension.com/maintaining-priorityqueue-order-with-java-streams/
If we have a look at PriorityQueue.iterator() documentation, we’ll see that, unintuitively, iterator() is not traversing the queue according to its priority order:
Returns an iterator over the elements in this queue. The iterator does not return the elements in any particular order
List<String> result = Stream.generate(queue::poll)
.limit(queue.size())
.collect(Collectors.toList());
Since Java 9, it’ll be possible to rewrite it in a concurrent-friendly manner:

static <T> Stream<T> drainToStream(PriorityQueue<T> queue) {
Objects.requireNonNull(queue);
return Stream.generate(queue::poll)
.takeWhile(Objects::nonNull)
}

https://stackoverflow.com/questions/47810524/is-collectingandthen-method-enough-efficient
collectingAndThen adds a single action that is just performed at the end of the collection.
So
String personWithMaxAge = persons.stream()
    .collect(Collectors.collectingAndThen(
        Collectors.maxBy(Comparator.comparing(Person::getAge)),
        (Optional<Person> p) -> p.isPresent() ? p.get().getName() : "none"
    ));
is not different to
Optional<Person> p = persons.stream()
    .collect(Collectors.maxBy(Comparator.comparing(Person::getAge)));
String personWithMaxAge = p.isPresent() ? p.get().getName() : "none";
The actual advantage of specifying the action within a collector shows when you use the resulting collector as input to another collect, e.g. groupingBy(f1, collectingAndThen(collector, f2)).
https://www.javabrahman.com/java-8/java-8-how-to-use-collectors-collectingandthen-method-with-examples/
Definition of Collectors.collectingAndThen() method
Collectors.collectingAndThen() method is defined with the following signature –
public static<T,A,R,RR> Collector<T,A,RR> collectingAndThen(Collector<T,A,R> downstream, Function<R,RR> finisher)
Where,
     – 1st input parameter is downstream which is an instance of a Collector<T,A,R> i.e. the standard definition of a collector. In other words, any collector can be used here.
     – 2nd input parameter is finisher which needs to be an instance of a Function<R,RR> functional interface. This function instance takes as input an object of type R which is the output from downstream collector, and it returns an output of type RR which is the final return type of collectingAndThen collector as well.
     – output is a Collector with finisher(return type) of type RR.
    String avgSalary = employeeList.stream().collect(
        Collectors.collectingAndThen(
            Collectors.averagingDouble(Employee::getSalary),
            averageSalary -> new DecimalFormat("'$'0.00").format(averageSalary)));

There is no reverse method for stream.

public static <T> Stream<T> reverse(Stream<T> stream) {
        LinkedList<T> stack = new LinkedList<>();
        stream.forEach(stack::push);
        return stack.stream();
    }
    public static void main(String[] args)
    {
        Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
        Stream<Integer> reverse = reverse(stream);
        reverse.forEach(System.out::println);
    }

    public static <T> Collector<T, ?, Stream<T>> reverse() {
        return Collectors.collectingAndThen(Collectors.toList(), list -> {
            Collections.reverse(list);
            return list.stream();
        });
    }
    public static void main(String[] args)
    {
        Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
        Stream<Integer> reverse = stream.collect(reverse());
        reverse.forEach(System.out::println);
    }
http://www.lambdafaq.org/what-are-the-reasons-for-the-restriction-to-effective-immutability/
Capture of local variables is restricted to those that are effectively final. Lifting this restriction would present implementation difficulties, but it would also be undesirable; its presence prevents the introduction of a new class of multithreading bugs involving local variables. Local variables in Java have until now been immune to race conditions and visibility problems because they are accessible only to the thread executing the method in which they are declared. But a lambda can be passed from the thread that created it to a different thread, and that immunity would therefore be lost if the lambda, evaluated by the second thread, were given the ability to mutate local variables. Even the ability to read the value of mutable local variables from a different thread would introduce the necessity for synchronization or the use of volatile in order to avoid reading stale data.
An alternative way to view this restriction is to consider the use cases that it discourages. Mutating local variables in idioms like this:
 int sum = 0;
 list.forEach(e -> { sum += e.size(); }); // illegal; local variable 'sum' is not effectively final
frustrates a principal purpose of introducing lambdas. The major advantage of passing a function to the forEach method is that it allows strategies that distribute evaluation of the function for different arguments to different threads. The advantage of that is lost if these threads have to be synchronized to avoid reading stale values of the captured variable.
The restriction of capture to effectively immutable variables is intended to direct developers’ attention to more easily parallelizable, naturally thread-safe techniques. For example, in contrast to the accumulation idiom above, the statement
 int sum = list.map(e -> e.size()).reduce(0, (a, b) -> a+b);
creates a pipeline in which the results of the evaluations of the map method can much more easily be executed in parallel, and subsequently gathered together by the reduce operation.

The restriction on local variables helps to direct developers using lambdas aways from idioms involving mutation; it does not prevent them. Mutable fields are always a potential source of concurrency problems if sharing is not properly managed; disallowing field capture by lambda expressions would reduce their usefulness without doing anything to solve this general problem.
http://www.lambdafaq.org/are-lambda-expressions-objects/
Yes, with a qualification: they are instances of object subtypes, but do not necessarily possess a unique identity. A lambda expression is an instance of a functional interface, which is itself a subtype of Object. To see this, consider the legal assignments:
    Runnable r = () -> {};   // creates a lambda expression and assigns a reference to this lambda to r 
    Object o = r;            // ordinary widening conversion 


But note that because lambdas do not necessarily possess a unique identity, the equals method inherited from Object has no consistent semantics.
https://stackoverflow.com/questions/24010109/java-8-stream-reverse-order
static IntStream revRange(int from, int to) {
    return IntStream.range(from, to)
                    .map(i -> to - i + from - 1);
}
This avoids boxing and sorting.
https://www.mkyong.com/java8/java-8-flatmap-example/
In Java 8, Stream can hold different data types, for examples:
Stream<String[]> 
Stream<Set<String>> 
Stream<List<String>> 
Stream<List<Object>>

But, the Stream operations (filter, sum, distinct…) and collectors do not support it, so, we need flatMap() to do the following conversion :
Stream<String[]>  -> flatMap -> Stream<String>
Stream<Set<String>> -> flatMap -> Stream<String>
Stream<List<String>> -> flatMap -> Stream<String>
Stream<List<Object>> -> flatMap -> Stream<Object>

How flatMap() works :
{ {1,2}, {3,4}, {5,6} } -> flatMap -> {1,2,3,4,5,6}

{ {'a','b'}, {'c','d'}, {'e','f'} } -> flatMap -> {'a','b','c','d','e','f'}

        String[][] data = new String[][]{{"a", "b"}, {"c", "d"}, {"e", "f"}};

        //Stream<String[]>
        Stream<String[]> temp = Arrays.stream(data);

        //Stream<String>, GOOD!
        Stream<String> stringStream = temp.flatMap(x -> Arrays.stream(x));

        Stream<String> stream = stringStream.filter(x -> "a".equals(x.toString()));

        stream.forEach(System.out::println);
http://massivetechinterview.blogspot.com/2015/10/java-8-stream.html
http://zetcode.com/java/streamreduce/
reduction is a terminal operation that aggregates a stream into a type or a primitive. The Java 8 Stream API contains a set of predefined reduction operations, such as average()sum()min(),max(), and count(), which return one value by combining the elements of a stream.

Stream.reduce() is a general-purpose method for generating our custom reduction operations.
Optional<T> reduce(BinaryOperator<T> accumulator)
This method performs a reduction on the elements of this stream, using an associative accumulation function. It returns an Optional describing the reduced value, if any.
T reduce(T identity, BinaryOperator<T> accumulator)
This method takes two parameters: the identity and the accumulator. The identity element is both the initial value of the reduction and the default result if there are no elements in the stream. The accumulator function takes two parameters: a partial result of the reduction and the next element of the stream. It returns a new partial result. The Stream.reduce() method returns the result of the reduction.


list.stream().reduce((x, y) -> x +"," + y)
 .ifPresent(s -> System.out.println("List to String: "+ s));

sum = list.stream().reduce(0, (x, y) -> x + y);


Labels

Review (561) System Design (304) System Design - Review (196) Java (179) Coding (75) Interview-System Design (65) Interview (60) Book Notes (59) Coding - Review (59) to-do (45) Knowledge (39) Linux (39) Interview-Java (35) Knowledge - Review (32) Database (31) Design Patterns (29) Product Architecture (28) Big Data (27) Soft Skills (27) Concurrency (26) MultiThread (26) Miscs (25) Cracking Code Interview (24) Distributed (23) Career (22) Interview - Review (21) Java - Code (21) Operating System (21) Interview Q&A (20) OOD Design (20) System Design - Practice (19) Security (17) How to Ace Interview (16) Algorithm (15) Brain Teaser (14) Redis (14) Google (13) Linux - Shell (13) Spark (13) Spring (13) Code Quality (12) How to (12) Interview-Database (12) Interview-Operating System (12) Tools (12) Architecture Principles (11) Company - LinkedIn (11) Testing (11) Resource (10) Search (10) Solr (10) Amazon (9) Cache (9) Web Dev (9) Architecture Model (8) Better Programmer (8) Company - Uber (8) Interview - MultiThread (8) Java67 (8) Math (8) OO Design principles (8) SOLID (8) Scalability (8) Cassandra (7) Company - Facebook (7) Design (7) Git (7) Interview Corner (7) JVM (7) Java Basics (7) Kafka (7) Machine Learning (7) NoSQL (7) Trouble Shooting (7) C++ (6) File System (6) Highscalability (6) How to Better (6) Network (6) Restful (6) CareerCup (5) Code Review (5) Hash (5) How to Interview (5) JDK Source Code (5) JavaScript (5) Leetcode (5) Must Known (5) API Design (4) Be Architect (4) Big Fata (4) C (4) Company Product Architecture (4) Data structures (4) Design Principles (4) Facebook (4) GeeksforGeeks (4) Generics (4) Google Interview (4) Hardware (4) JDK8 (4) Optimization (4) Product + Framework (4) Puzzles (4) Python (4) Shopping System (4) Source Code (4) Web Service (4) node.js (4) Back-of-Envelope (3) Company - Pinterest (3) Company - Twiiter (3) Company - Twitter (3) Consistent Hash (3) Elasticsearch (3) GOF (3) Game Design (3) GeoHash (3) Growth (3) Guava (3) Interview-Big Data (3) Interview-Linux (3) Interview-Network (3) Java EE Patterns (3) Javarevisited (3) Map Reduce (3) Math - Probabilities (3) Performance (3) RateLimiter (3) Resource-System Desgin (3) Scala (3) UML (3) ZooKeeper (3) geeksquiz (3) AI (2) Advanced data structures (2) AngularJS (2) Behavior Question (2) Bugs (2) Coding Interview (2) Company - Netflix (2) Crawler (2) Cross Data Center (2) Data Structure Design (2) Database-Shard (2) Debugging (2) Docker (2) Garbage Collection (2) Go (2) Hadoop (2) Html (2) Interview - Soft Skills (2) Interview-Miscs (2) Interview-Web (2) JDK (2) Logging (2) POI (2) Papers (2) Programming (2) Project Practice (2) Random (2) Software Desgin (2) System Design - Feed (2) Thread Synchronization (2) Video (2) reddit (2) Ads (1) Algorithm - Review (1) Android (1) Approximate Algorithms (1) Base X (1) Bash (1) Books (1) C# (1) CSS (1) Chrome (1) Client-Side (1) Cloud (1) CodingHorror (1) Company - Yelp (1) Counter (1) DSL (1) Dead Lock (1) Difficult Puzzles (1) Distributed ALgorithm (1) Eclipse (1) Facebook Interview (1) Function Design (1) Functional (1) GoLang (1) How to Solve Problems (1) ID Generation (1) IO (1) Important (1) Internals (1) Interview - Dropbox (1) Interview - Project Experience (1) Interview Stories (1) Interview Tips (1) Interview-Brain Teaser (1) Interview-How (1) Interview-Mics (1) Interview-Process (1) Java Review (1) Jeff Dean (1) Joda (1) LeetCode - Review (1) Library (1) LinkedIn (1) LintCode (1) Mac (1) Micro-Services (1) Mini System (1) MySQL (1) Nigix (1) NonBlock (1) Process (1) Productivity (1) Program Output (1) Programcreek (1) Quora (1) RPC (1) Raft (1) Reactive (1) Reading (1) Reading Code (1) Refactoring (1) Resource-Java (1) Resource-System Design (1) Resume (1) SQL (1) Sampling (1) Shuffle (1) Slide Window (1) Spotify (1) Stability (1) Storm (1) Summary (1) System Design - TODO (1) Tic Tac Toe (1) Time Management (1) Web Tools (1) algolist (1) corejavainterviewquestions (1) martin fowler (1) mitbbs (1)

Popular Posts