Java 8 Tips

This blog is listing key new features introduced in Java 8

It is best to think of a lambda expression as a function, not an object, and to accept that it can be converted to a functional interface.

Clean Code in Java 8

Here is the sample code in Java 8

calss DiscountService{
   Integer discount =getDiscountPercentage(customer.getMemberCard());
}

New comparator method in Java 8

List<Track> tracks = asList(new Track("Bakai", 524),
                            new Track("Violets for Your Furs", 378),
                            new Track("Time Was", 451));

Track shortestTrack = tracks.stream()
                            .min(Comparator.comparing(track -> track.getLength()))
                            .get();

assertEquals(tracks.get(1), shortestTrack);

When we think about maximum and minimum elements, the first thing we need to think about is the ordering that we’re going to be using. When it comes to finding the shortest track, the ordering is provided by the length of the ”

In order to inform the Stream that we’re using the length of the track, we give it a Comparator. Conveniently, Java 8 has added a static method called comparing that lets us build a comparator using keys. Previously, we always encountered an ugly pattern in which we had to write code that got a field out of both the objects being compared, then compare these field values. Now, to get the same element out of both elements being compared, we just provide a getter function for the value. In this case we’ll use length, which is a getter function in disguise. It’s worth reflecting on the comparing method for a moment. This is actually a function that takes a function and returns a function. Pretty meta, I know, but also incredibly useful. At any point in the past, this method could have been added to the Java standard library, but the poor readability and verbosity issues surrounding anonymous inner classes would have made it impractical. Now, with lambda expressions, it’s convenient and concise. ” But thinking of passing code to methods as a mere consequence of Streamsdownplays its range of uses within Java 8. It gives you a new concise way to express behavior parameterization.

It might sound surprising, but interfaces in Java 8 can now declare methods with implementation code; this can happen in two ways. First, Java 8 allows static methods inside interfaces. Second, Java 8 introduces a new feature called default methods that allows you to provide a default implementation for methods in an interface. In other words, interfaces can provide concrete implementation for methods. As a result, existing classes implementing an interface will automatically inherit the default implementations if they don’t provide one explicitly. This allows you to evolve interfaces nonintrusively. You’ve been using several default methods all along. Two examples you’ve seen are sort in the List interface and stream in the Collection interface. Wow! Are interfaces like abstract classes now? Yes and no; there are fundamental differences, which we explain in this chapter. But more important, why should you care about default methods? The main users of default methods are library designers. As we explain later, default methods were introduced to evolve libraries such as the Java API in a compatible way,

Now that static methods can exist inside interfaces, such utility classes in your code can go away and their static methods can be moved inside an interface. These companion classes will remain in the Java API in order to preserve backward compatibility. Adding a new method to an interface is binary compatible; this means existing class file implementations will still run without the implementation of the new method, if there’s no attempt to recompile them. In this case the game will still run (unless it’s recompiled) despite adding the method setRelativeSize to the Resizable interface

Abstract classes vs. interfaces in Java 8

So what’s the difference between an abstract class and an interface? They both can contain abstract methods and methods with a body.

  • First, a class can extend only from one abstract class, but a class can implement multiple interfaces.

  • Second, an abstract class can enforce a common state through instance variables (fields). An interface can’t have instance variables.

Keeping interfaces minimal and orthogonal lets you achieve great reuse and composition of behavior inside your codebase.

Minimal interfaces with orthogonal functionalities Inheritance considered harmful Inheritance shouldn’t be your answer to everything when it comes down to reusing code. For example, inheriting from a class that has 100 methods and fields just to reuse one method is a bad idea, because it adds unnecessary complexity. You’d be better off using delegation: create a method that calls directly the method of the class you need via a member variable. This is why you’ll sometime find classes that are declared “final” intentionally: they can’t be inherited from to prevent this kind of antipattern or have their core behavior messed with. Note that sometimes final classes have a place; for example, String is final because we don’t want anybody to be able to interfere with such core functionality.

Three resolution rules to know

There are three rules to follow when a class inherits a method with the same signature from multiple places (such as another class or interface):

  1. Classes always win. A method declaration in the class or a superclass takes priority over any default method declaration.

  2. Otherwise, sub-interfaces win: the method with the same signature in the most specific default-providing interface is selected. (If B extends A, B is more specific than A).

  3. Finally, if the choice is still ambiguous, the class inheriting from multiple interfaces has to explicitly select which default method implementation to use by overriding it and calling the desired method explicitly.

These are the only rules you need to know!

Lambda Interfaces

This conversion to interfaces is what makes lambda expressions so compelling. The syntax is short and simple.

BiFunction<String, String, Integer> comp
   = (first, second) -> Integer.compare(first.length(), second.length());

The expression System.out::printlnis a method reference that is equivalent to the lambda expression x -> System.out.println(x).

There are three principal cases:

  • object::instanceMethod
  • Class::staticMethod
  • Class::instanceMethod

In the third case, the first parameter becomes the target of the method. For example, String::compareToIgnoreCaseis the same as (x, y) -> x.compareToIgnoreCase(y).

Just like lambda expressions, method references don’t live in isolation. They are always turned into instances of functional interfaces.

Constructor References

Constructor references are just like method references, except that the name of the method is newå. For example, Button::new is a reference to a Button constructor. Which constructor? It depends on the context.

List<String> labels = ...;
Stream<Button> stream = labels.stream().map(Button::new);
List<Button> buttons = stream.collect(Collectors.toList());

For example, suppose we want to have an array of buttons. The Stream interface has a toArraymethod that returns an Object array:

Object[] buttons = stream.toArray();

we need to refine our understanding of a lambda expression. A lambda expression has three ingredients:

  1. A block of code
  2. Parameters
  3. Values for the free variables, that is, the variables that are not parameters and not defined inside the code

The technical term for a block of code together with the values of the free variables is a closure. If someone gloats that their language has closures, rest assured that Java has them as well. In Java, lambda expressions are closures. In fact, inner classes have been closures all along. Java 8 gives us closures with an attractive syntax.

Inner classes can also capture values from an enclosing scope. Before Java 8, inner classes were only allowed to access finallocal variables. This rule has now been relaxed to match that for lambda expressions. An inner class can access any effectively final local variable—that is, any variable whose value does not change.

When you use the this keyword in a lambda expression, you refer to the this parameter of the method that creates the lambda. For example, consider

public class Application {
   public void doWork() {
      Runnable runner = () -> { ...; System.out.println(this.toString()); ... };
      ...
   }
}

The expression this.toString()calls the toString method of the Application object, not the Runnable instance. There is nothing special about the use of this in a lambda expression. The scope of the lambda expression is nested inside the doWork method, and this has the same meaning anywhere in that method.

default methods

The Java designers decided to solve this problem once and for all by allowing interface methods with concrete implementations (called default methods). Those methods can be safely added to existing interfaces.

interface Person {
   long getId();
   default String getName() { return "John Q. Public"; }
}

The interface has two methods: getId, which is an abstract method, and the default method getName. A concrete class that implements the Person interface must, of course, provide an implementation of getId, but it can choose to keep the implementation of getName or to override it.

Default methods put an end to the classic pattern of providing an interface and an abstract class that implements most or all of its methods, such as Collection/AbstractCollectionor/WindowListener/WindowAdapter. Now you can just implement the methods in the interface.

To compare Person objects by name, use Comparator.comparing(Person::getName).

we have compared strings by length with the lambda expression

(first, second) -> Integer.compare(first.length(), second.length()). 

But with the static compare method, we can do much better and simply use

Comparator.comparing(String::length).

In Java 8, static methods have been added to quite a few interfaces. For example, the Comparator interface has a very useful static comparing method that accepts a “key extraction” function and yields a comparator that compares the extracted keys.

Stream vs collections

A stream seems superficially similar to a collection, allowing you to transform and retrieve data. But there are significant differences:

  • A stream does not store its elements. They may be stored in an underlying collection or generated on demand.
  • Stream operations don’t mutate their source. Instead, they return new streams that hold the result.
  • Stream operations are lazy when possible. This means they are not executed until their result is needed. For example, if you only ask for the first five long words instead of counting them all, then the filter method will stop filtering after the fifth match. As a consequence, you can even have infinite streams!

Streams follow the “what, not how” principle. In our stream example, we describe what needs to be done: get the long words and count them. We don’t specify in which order, or in which thread, this should happen.

Work with streams

When you work with streams, you set up a pipeline of operations in three stages.

  1. You create a stream.
  2. You specify intermediate operations for transforming the initial stream into others, in one or more steps.
  3. You apply a terminal operation to produce a result. This operation forces the execution of the lazy operations that precede it. Afterwards, the stream can no longer be used.
long count = words.parallelStream().filter(w -> w.length() > 12).count();

Stream operations are not executed on the elements in the order in which they are invoked on the streams. In our example, nothing happens until count is called. When the count method asks for the first element, then the filter method starts requesting elements, until it finds one that has length > 12.

To produce infinite sequences such as 0 1 2 3 …, use the iterate method instead. It takes a “seed” value and a function (technically, a UnaryOperator), and repeatedly applies the function to the previous result. For example,

Stream<BigInteger> integers
   = Stream.iterate(BigInteger.ZERO, n -> n.add(BigInteger.ONE));

The first element in the sequence is the seed

You can use the following statement to split a string into words:

Stream<String> words
   = Pattern.compile("[\\P{L}]+").splitAsStream(contents);

The static Files.linesmethod returns a Stream of all lines in a file.

The Stream interface has AutoCloseableas a superinterface. When the close method is called on the stream, the underlying file is also closed.

To make sure that this happens, it is best to use the Java 7 try-with-resources statement:

try (Stream<String> lines = Files.lines(path)) {
   Do something with lines
}

The stream, and the underlying file with it, will be closed when the try block exits normally or through an exception.

The filter, map, and flatMapMethods A stream transformation reads data from a stream and puts the transformed data into another stream. You have already seen the filter transformation that yields a new stream with all elements that match a certain condition.

2.3. The filter, map, and flatMap Methods A stream transformation reads data from a stream and puts the transformed data into another stream. You have already seen the filtertransformation that yields a new stream with all elements that match a certain condition. Here, we transform a stream of strings into another stream containing only long words:

List<String> wordList = ...;
Stream<String> words = wordList.stream();
Stream<String> longWords = words.filter(w -> w.length() > 12);

The argument of filter is a Predicate—that is, a function from T to boolean.

Often, you want to transform the values in a stream in some way. Use the map method and pass the function that carries out the transformation. For example, you can transform all words to lowercase like this:

Stream<String> lowercaseWords = words.map(String::toLowerCase);

Here, we used mapwith a method reference. Often, you will use a lambda expression instead:

Stream<Character> firstChars = words.map(s -> s.charAt(0));

The resulting stream contains the first character of each word.

When you use map, a function is applied to each element, and the return values are collected in a new stream. Now suppose that you have a function that returns not just one value but a stream of values, such as this one:

public static Stream<Character> characterStream(String s) {
   List<Character> result = new ArrayList<>();
   for (char c : s.toCharArray()) result.add(c);
   return result.stream();
}

For example, characterStream(“boat”)is the stream [‘b’, ‘o’, ‘a’, ‘t’]. Suppose you map this method on a stream of strings:

Stream<Stream<Character>> result = words.map(w -> characterStream(w));

You will get a stream of streams, like [… [‘y’, ‘o’, ‘u’, ‘r’], [‘b’, ‘o’, ‘a’, ‘t’], …] To flatten it out to a stream of characters [… ‘y’, ‘o’, ‘u’, ‘r’, ‘b’, ‘o’, ‘a’, ‘t’, …], use the flatMapmethod instead of map:

Stream<Character> letters = words.flatMap(w -> characterStream(w))
    // CallscharacterStream on each word and flattens the results

NOTE

You may find a flatMap method in classes other than streams. It is a general concept in computer science. Suppose you have a generic type G (such as Stream) and functions ffrom some type T to Gand g from U to G. Then you can compose them, that is, first apply f and then g, by using flatMap. This is a key idea in the theory of monads. But don’t worry—you can use flatMapwithout knowing anything about monads.

This method is particularly useful for cutting infinite streams down to size. For example,

Stream<Double> randoms = Stream.generate(Math::random).limit(100);

yields a stream with 100 random numbers.

The peek method yields another stream with the same elements as the original, but a function is invoked every time an element is retrieved. That is handy for debugging:

Object[] powers = Stream.iterate(1.0, p -> p * 2)
   .peek(e -> System.out.println("Fetching " + e))
   .limit(20).toArray();

When an element is actually accessed, a message is printed. This way you can verify that the infinite stream returned by iterate is processed lazily.

The stream transformations of the preceding sections were stateless. When an element is retrieved from a filtered or mapped stream, the answer does not depend on the previous elements. There are also a few stateful transformations. For example, the distinct method returns a stream that yields elements from the original stream, in the same order, except that duplicates are suppressed.

The stream must obviously remember the elements that it has already seen.

Stream<String> uniqueWords
   = Stream.of("merrily", "merrily", "merrily", "gently").distinct();
   // Only one"merrily" is retained

The sorted method must see the entire stream and sort it before it can give out any elements—after all, the smallest one might be the last one. Clearly, you can’t sort an infinite stream.

There are several sorted methods. One works for streams of Comparableelements, and another accepts a Comparator. Here, we sort strings so that the longest ones come first:

Click here to view code image

Stream longestFirst = words.sorted(Comparator.comparing(String::length).reversed()); Of course, you can sort a collection without using streams. The sorted method is useful when the sorting process is a part of a stream pipeline.

NOTE

The Collections.sortmethod sorts a collection in place, whereas Stream.sortedreturns a new sorted stream.

The methods that we cover in this section are called reductions. They reduce the stream to a value that can be used in your program. Reductions are terminal operations. After a terminal operation has been applied, the stream ceases to be usable.

In Java 8, the Optional type is the preferred way of indicating a missing return value. We discuss the Optional type in detail in the next section. Here is how you can get the maximum of a stream:

Click here to view code image

Optional largest = words.max(String::compareToIgnoreCase); if (largest.isPresent()) System.out.println("largest: " + largest.get());

reduce. Each segment needs to start out with its own empty hash set, and reduce only lets you supply one identity value. Instead, use collect. It takes three arguments:

  1. A supplier to make new instances of the target object, for example, a constructor for a hash set

  2. An accumulatorthat adds an element to the target, for example, an addmethod

  3. A combiner that merges two objects into one, such as addAll

NOTE

The target object need not be a collection. It could be a StringBuilderor an object that tracks a count and a sum.

Here is how the collect method works for a hash set:

Click here to view code image

HashSet result = stream.collect(HashSet::new, HashSet::add, HashSet::addAll);

In practice, you don’t have to do that because there is a convenient Collector interface for these three functions, and a Collectors class with factory methods for common collectors. To collect a stream into a list or set, you can simply call

Click here to view code image

List result = stream.collect(Collectors.toList());

or

Click here to view code image

Set result = stream.collect(Collectors.toSet());

If you want to control which kind of set you get, use the following call instead:

Click here to view code image

TreeSet result = stream.collect(Collectors.toCollection(TreeSet::new));

Suppose you want to collect all strings in a stream by concatenating them. You can call

String result = stream.collect(Collectors.joining());

If you want a delimiter between elements, pass it to the joiningmethod:

Click here to view code image

String result = stream.collect(Collectors.joining(“, “));

If your stream contains objects other than strings, you need to first convert them to strings, like this:

Click here to view code image

String result = stream.map(Object::toString).collect(Collectors.joining(“, “));

If you want to reduce the stream results to a sum, average, maximum, or minimum, then use one of the methods summarizing(Int Long Double). These methods take a function that maps the stream objects to a number and yield a result of type (Int Long Double)SummaryStatistics, with methods for obtaining the sum, average, maximum, and minumum.

Click here to view code image

IntSummaryStatistics summary = words.collect( Collectors.summarizingInt(String::length)); double averageWordLength = summary.getAverage(); double maxWordLength = summary.getMax();

NOTE

So far, you have seen how to reduce or collect stream values. But perhaps you just want to print them or put them in a database. Then you can use the forEachmethod:

stream.forEach(System.out::println);

The function that you pass is applied to each element. On a parallel stream, it’s your responsibility to ensure that the function can be executed concurrently. We discuss this in Section 2.13, “Parallel Streams,” on page 40.

On a parallel stream, the elements can be traversed in arbitrary order. If you want to execute them in stream order, call forEachOrderedinstead. Of course, you might then give up most or all of the benefits of parallelism.

The forEachand forEachOrderedmethods are terminal operations. You cannot use the stream again after calling them. If you want to continue using the stream, use peekinstead—see

In the common case that the values should be the actual elements, use Function.identity()for the second function.

Click here to view code image

Map<Integer, Person> idToPerson = people.collect( Collectors.toMap(Person::getId, Function.identity())); If there is more than one element with the same key, the collector will throw an IllegalStateException. You can override that behavior by supplying a third function argument that determines the value for the key, given the existing and the new value. Your function could return the existing value, the new value, or a combination of them.

Here, we construct a map that contains, for each language in the available locales, as key its name in your default locale (such as “German”), and as value its localized name (such as “Deutsch”).

Click here to view code image

Stream locales = Stream.of(Locale.getAvailableLocales()); Map<String, String> languageNames = locales.collect( Collectors.toMap( l -> l.getDisplayLanguage(), l -> l.getDisplayLanguage(l), (existingValue, newValue) -> existingValue)); We don’t care that the same language might occur twice—for example, German in Germany and in Switzerland, and we just keep the first entry.

However, suppose we want to know all languages in a given country. Then we need a Map<String, Set>. For example, the value for "Switzerland"is the set [French, German, Italian]. At first, we store a singleton set for each language. Whenever a new language is found for a given country, we form the union of the existing and the new set.

Click here to view code image

Map<String, Set> countryLanguageSets = locales.collect( Collectors.toMap( l -> l.getDisplayCountry(), l -> Collections.singleton(l.getDisplayLanguage()), (a, b) -> { // Union of a and b Set r = new HashSet<>(a); r.addAll(b); return r; })); You will see a simpler way of obtaining this map in the next section.

If you want a TreeMap, then you supply the constructor as the fourth argument. You must provide a merge function. Here is one of the examples from the beginning of the section, now yielding a TreeMap:

Click here to view code image

Map<Integer, Person> idToPerson = people.collect( Collectors.toMap( Person::getId, Function.identity(), (existingValue, newValue) -> { throw new IllegalStateException(); }, TreeMap::new));

For example, if you want sets instead of lists, you can use the Collectors.toSetcollector that you saw in the preceding section:

Click here to view code image

Map<String, Set> countryToLocaleSet = locales.collect( groupingBy(Locale::getCountry, toSet()));

Several other collectors are provided for downstream processing of grouped elements:

• countingproduces a count of the collected elements. For example,

Click here to view code image

Map<String, Long> countryToLocaleCounts = locales.collect( groupingBy(Locale::getCountry, counting())); counts how many locales there are for each country.

• summing(Int Long Double) takes a function argument, applies the function to the downstream elements, and produces their sum. For example,

Click here to view code image

Map<String, Integer> stateToCityPopulation = cities.collect( groupingBy(City::getState, summingInt(City::getPopulation))); computes the sum of populations per state in a stream of cities.

• maxBy and minBytake a comparator and produce maximum and minimum of the downstream elements. For example,

Click here to view code image

Map<String, City> stateToLargestCity = cities.collect( groupingBy(City::getState, maxBy(Comparator.comparing(City::getPopulation)))); produces the largest city per state.

• mapping applies a function to downstream results, and it requires yet another collector for processing its results. For example,

Click here to view code image

Map<String, Optional> stateToLongestCityName = cities.collect( groupingBy(City::getState, mapping(City::getName, maxBy(Comparator.comparing(String::length))))); Here, we group cities by state. Within each state, we produce the names of the cities and reduce by maximum length.

The mappingmethod also yields a nicer solution to a problem from the preceding section, to gather a set of all languages in a country.

Click here to view code image

Map<String, Set> countryToLanguages = locales.collect( groupingBy(l -> l.getDisplayCountry(), mapping(l -> l.getDisplayLanguage(), toSet()))); In the preceding section, I used toMap instead of groupingBy. In this form, you don’t need to worry about combining the individual sets.

• If the grouping or mapping function has return type int, long, or double, you can collect elements into a summary statistics object, as discussed in Section 2.9, “Collecting Results,” on page 33. For example,

Click here to view code image

Map<String, IntSummaryStatistics> stateToCityPopulationSummary = cities.collect( groupingBy(City::getState, summarizingInt(City::getPopulation))); Then you can get the sum, count, average, minimum, and maximum of the function values from the summary statistics objects of each group.

• Finally, the reducingmethods apply a general reduction to downstream elements. There are three forms: reducing(binaryOperator), reducing(identity, binaryOperator), and reducing(identity, mapper, binaryOperator). In the first form, the identity is null. (Note that this is different from the forms of Stream::reduce, where the method without an identity parameter yields an Optional result.) In the third form, the mapperfunction is applied and its values are reduced.

Here is an example that gets a comma-separated string of all city names in each state. We map each city to its name and then concatenate them.

Click here to view code image

Map<String, String> stateToCityNames = cities.collect( groupingBy(City::getState, reducing(“”, City::getName, (s, t) -> s.length() == 0 ? t : s + “, “ + t))); As with Stream.reduce, Collectors.reducingis rarely necessary. In this case, you can achieve the same result more naturally as

Click here to view code image

Map<String, String> stateToCityNames = cities.collect( groupingBy(City::getState, mapping(City::getName, joining(“, “)))); Frankly, the downstream collectors can yield very convoluted expressions. You should only use them in connection with groupingBy or partitioningBy to process the “downstream” map values. Otherwise, simply apply methods such as map, reduce, count, max, or mindirectly on streams.

2.12. Primitive Type Streams So far, we have collected integers in a Stream, even though it is clearly inefficient to wrap each integer into a wrapper object. The same is true for the other primitive types double, float, long, short, char, byte, and boolean. The stream library has specialized types IntStream, LongStream, and DoubleStream that store primitive values directly, without using wrappers. If you want to store short, char, byte, and boolean, use an IntStream, and for float, use a DoubleStream. The library designers didn’t think it was worth adding another five stream types.

To create an IntStream, you can call the IntStream.of and Arrays.streammethods:

Click here to view code image

IntStream stream = IntStream.of(1, 1, 2, 3, 5); stream = Arrays.stream(values, from, to); // values is an int[] array As with object streams, you can also use the static generate and iterate methods. In addition, IntStreamand LongStreamhave static methods range and rangeClosed that generate integer ranges with step size one:

Click here to view code image

IntStream zeroToNinetyNine = IntStream.range(0, 100); // Upper bound is excluded IntStream zeroToHundred = IntStream.rangeClosed(0, 100); // Upper bound is included The CharSequenceinterface has methods codePoints and chars that yield an IntStream of the Unicode codes of the characters or of the code units in the UTF-16 encoding. (If you don’t know what code units are, you probably shouldn’t use the chars method. Read up on the sordid details in Core Java, 9th Edition, Volume 1, Section 3.3.3.)

Click here to view code image

String sentence = “\uD835\uDD46 is the set of octonions.”; // \uD835\uDD46 is the UTF-16 encoding of the letter

, unicode U+1D546

IntStream codes = sentence.codePoints(); // The stream with hex values 1D546 20 69 73 20 … When you have a stream of objects, you can transform it to a primitive type stream with the mapToInt, mapToLong, or mapToDoublemethods. For example, if you have a stream of strings and want to process their lengths as integers, you might as well do it in an IntStream:

Click here to view code image

Stream words = ...; IntStream lengths = words.mapToInt(String::length); To convert a primitive type stream to an object stream, use the boxed method:

Click here to view code image

Stream integers = IntStream.range(0, 100).boxed();

Generally, the methods on primitive type streams are analogous to those on object streams. Here are the most notable differences:

• The toArraymethods return primitive type arrays.

• Methods that yield an optional result return an OptionalInt, OptionalLong, or OptionalDouble. These classes are analogous to the Optional class, but they have methods getAsInt, getAsLong, and getAsDoubleinstead of the getmethod.

• There are methods sum, average, max, and min that return the sum, average, maximum, and minimum. These methods are not defined for object streams.

• The summaryStatisticsmethod yields an object of type IntSummaryStatistics, LongSummaryStatistics, or DoubleSummaryStatisticsthat can simultaneously report the sum, average, maximum, and minimum of the stream.

NOTE

The Randomclass has methods ints, longs, and doubles that return primitive type streams of random numbers.

2.13. Parallel Streams Streams make it easy to parallelize bulk operations. The process is mostly automatic, but you need to follow a few rules. First of all, you must have a parallel stream. By default, stream operations create sequential streams, except for Collection.parallelStream(). The parallelmethod converts any sequential stream into a parallel one. For example:

Click here to view code image

Stream parallelWords = Stream.of(wordArray).parallel();

As long as the stream is in parallel mode when the terminal method executes, all lazy intermediate stream operations will be parallelized.

When stream operations run in parallel, the intent is that the same result is returned as if they had run serially. It is important that the operations are stateless and can be executed in an arbitrary order.

Here is an example of something you cannot do. Suppose you want to count all short words in a stream of strings:

Click here to view code image

int[] shortWords = new int[12]; words.parallel().forEach( s -> { if (s.length() < 12) shortWords[s.length()]++; }); // Error—race condition! System.out.println(Arrays.toString(shortWords)); This is very, very bad code. The function passed to forEachruns concurrently in multiple threads, updating a shared array. That’s a classic race condition. If you run this program multiple times, you are quite likely to get a different sequence of counts in each run, each of them wrong.

It is your responsibility to ensure that any functions that you pass to parallel stream operations are threadsafe. In our example, you could use an array of AtomicIntegerobjects for the counters (see Exercise 12). Or you could simply use the facilities of the streams library and group strings by length (see Exercise 13).

By default, streams that arise from ordered collections (arrays and lists), from ranges, generators, and iterators, or from calling Stream.sorted, are ordered. Results are accumulated in the order of the original elements, and are entirely predictable. If you run the same operations twice, you will get exactly the same results.

Ordering does not preclude parallelization. For example, when computing stream.map(fun), the stream can be partitioned into nsegments, each of which is concurrently processed. Then the results are reassembled in order.

Some operations can be more effectively parallelized when the ordering requirement is dropped. By calling the Stream.unorderedmethod, you indicate that you are not interested in ordering. One operation that can benefit from this is Stream.distinct. On an ordered stream, distinct retains the first of all equal elements. That impedes parallelization—the thread processing a segment can’t know which elements to discard until the preceding segment has been processed. If it is acceptable to retain any of the unique elements, all segments can be processed concurrently (using a shared set to track duplicates).

You can also speed up the limit method by dropping ordering. If you just want any nelements from a stream and you don’t care which ones you get, call

Click here to view code image

Stream sample = stream.parallel().unordered().limit(n);

As discussed in Section 2.10, “Collecting into Maps,” on page 34, merging maps is expensive. For that reason, the Collectors.groupingByConcurrentmethod uses a shared concurrent map. Clearly, to benefit from parallelism, the order of the map values will not be the same as the stream order. Even on an ordered stream, that collector has a “characteristic” of being unordered, so that it can be used efficiently without having to make the stream unordered. You still need to make the stream parallel, though:

Click here to view code image

Map<String, List> result = cities.parallel().collect( Collectors.groupingByConcurrent(City::getState)); // Values aren’t collected in stream order

CAUTION

It is very important that you don’t modify the collection that is backing a stream while carrying out a stream operation (even if the modification is threadsafe). Remember that streams don’t collect their own data—the data is always in a separate collection. If you were to modify that collection, the outcome of the stream operations would be undefined. The JDK documentation refers to this requirement as noninterference. It applies both to sequential and parallel streams.

To be exact, since intermediate stream operations are lazy, it is possible to mutate the collection up to the point when the terminal operation executes. For example, the following is correct:

Click here to view code image

List wordList = ...; Stream words = wordList.stream(); wordList.add("END"); // Ok long n = words.distinct().count(); But this code is not:

Click here to view code image

Stream words = wordList.stream(); words.forEach(s -> if (s.length() < 12) wordList.remove(s)); // Error—interference

Exercises

  1. Write a parallel version of the forloop in Section 2.1, “From Iteration to Stream Operations,” on page 22. Obtain the number of processors. Make that many separate threads, each working on a segment of the list, and total up the results as they come in. (You don’t want the threads to update a single counter. Why?)

  2. Verify that asking for the first five long words does not call the filter method once the fifth long word has been found. Simply log each method call.

  3. Measure the difference when counting long words with a parallelStreaminstead of a stream. Call System.nanoTimebefore and after the call, and print the difference. Switch to a larger document (such as War and Peace) if you have a fast computer.

  4. Suppose you have an array int[] values = { 1, 4, 9, 16 }. What is Stream.of(values)? How do you get a stream of intinstead?

  5. Using Stream.iterate, make an infinite stream of random numbers—not by calling Math.random but by directly implementing a linear congruential generator. In such a generator, you start with x0 = seedand then produce xn + 1 = (a xn + c) %m, for appropriate values of a, c, and m. You should implement a method with parameters a, c, m, and seed that yields a Stream. Try out a = 25214903917, c = 11, and m = 248.

  6. The characterStreammethod in Section 2.3, “The filter, map, and flatMapMethods,” on page 25, was a bit clumsy, first filling an array list and then turning it into a stream. Write a stream-based one-liner instead. One approach is to make a stream of integers from 0 to s.length() - 1and map that with the s::charAtmethod reference.

  7. Your manager asks you to write a method public static boolean isFinite(Stream stream). Why isn’t that such a good idea? Go ahead and write it anyway.

  8. Write a method public static Stream zip(Stream first, Stream second) that alternates elements from the streams first and second, stopping when one of them runs out of elements.

  9. Join all elements in a Stream<ArrayList>to one ArrayList. Show how to do this with the three forms of reduce.

  10. Write a call to reduce that can be used to compute the average of a Stream. Why can’t you simply compute the sum and divide by count()?

  11. It should be possible to concurrently collect stream results in a single ArrayList, instead of merging multiple array lists, provided it has been constructed with the stream’s size, since concurrent setoperations at disjoint positions are threadsafe. How can you achieve that?

  12. Count all short words in a parallel Stream, as described in Section 2.13, “Parallel Streams,” on page 40, by updating an array of AtomicInteger. Use the atomic getAndIncrementmethod to safely increment each counter.

  13. Repeat the preceding exercise, but filter out the short strings and use the collectmethod with Collectors.groupingByand Collectors.counting.

A function type is alwayscontravariant in its arguments and covariant in its return value. For example, if you have a Function<Person, Employee>, you can safely pass it on to someone who needs a Function<Employee, Person>. They will only call it with employees, whereas your function can handle any person. They will expect the function to return a person, and you give them something even better.

For example, look at the javadoc for Stream:

Click here to view code image

void forEach(Consumer<? super T> action) Stream filter(Predicate<? super T> predicate)

Stream map(Function<? super T, ? extends R> mapper) The general rule is that you use superfor argument types, extends for return types. That way, you can pass a Consumerto forEach on a Stream. If it is willing to consume any object, surely it can consume strings. But the wildcards are not always there. Look at For example, consider the doInOrderAsyncmethod of the preceding section. Instead of Click here to view code image public static void doInOrderAsync(Supplier first, Consumer second, Consumer handler) it should be Click here to view code image public static void doInOrderAsync(Supplier<? extends T> first, Consumer<? super T> second, Consumer<? superThrowable> handler) In our example, we can call Click here to view code image largest.updateAndGet(x -> Math.max(x, observed)); or Click here to view code image largest.accumulateAndGet(observed, Math::max); The accumulateAndGetmethod takes a binary operator that is used to combine the atomic value and the supplied argument. ## **default** in Java ### There are three rules about **default** Regarding how to handle the situation of same default method in multiple inheritance. - **class win**, any class wins over any interfaces.So if there’s a method with a body, or an abstract declaration, in the superclass chain, we can ignore the interfaces completely. - **subtype win supertype**, “which two interfaces are competing to provide a default method and one interface extends the other, the subclass wins.” - **No rule 3**. if the previous two rules don't give us the answer, the subclass must either implement the method or declare it **abstract**. “Interfaces give you multiple inheritance but no fields, while abstract classes let you “inherit fields but you don’t get multiple inheritance.” ## Static method in Interface We’ve seen a lot of calling of **Stream.of** but haven’t gotten into its details yet. You may recall that Stream is an interface, but this is a static method on an interface. ```java stream.collect(toCollection(TreeSet::new)); ``` # **Optional** is a better of **null** ```java //Optional can be created via factory method 'of', Optional a = Optional.of("a"); // Optional is just a container, you can get the underlying value by 'get' method assertEquals("a", a.get()); // at the meanwhile, Optional can represent 'absent' // factory method empty or ofNullable from a nullable object can be used @Test public void testOptional(){ Optional optA=Optional.of("a"); Assert.assertEquals("a", optA.get()); } @Test public void testEmpty(){ Optional emp=Optional.ofNullable(null); Assert.assertEquals(Optional.empty(), emp); Assert.assertFalse(emp.isPresent()); Assert.assertEquals("b", emp.orElse("b")); Assert.assertEquals("c", emp.orElseGet(()->"c")); } ``` # method reference - ** Classname::methodname** , such as Artist::getName is equivalant to artist->artist.getName() - For constructors can be used Artist::new - You can alos to create new array, String[]::new # Stream “The purpose of streams isn’t just to convert from one collection to another; it’s to be able to provide a common set of operations over data.” ## partitioningBy To split a stream into two groups, one for 'trueGroup' and another group ## Lanmbda - It is best to think of a lambda expression as a function, not an object, and to accept that it can be converted to a functional interface. - This conversion to interfaces is what makes lambda expressions so compelling. The syntax is short and simple. ```java BiFunction<String, String, Integer> comp = (first, second) -> Integer.compare(first.length(), second.length()); ``` The expression System.out::printlnis a method reference that is equivalent to the lambda expression x -> System.out.println(x). ### There are three principal cases: - object::instanceMethod - Class::staticMethod - Class::instanceMethod In the third case, the first parameter becomes the target of the method. For example, String::compareToIgnoreCaseis the same as (x, y) -> x.compareToIgnoreCase(y). Just like lambda expressions, method references don’t live in isolation. They are always turned into instances of functional interfaces. ### Constructor References Constructor references are just like method references, except that the name of the method is new. For example, Button::new is a reference to a Button constructor. Which constructor? It depends on the context. ```java List labels = ...; Stream

2022

Linux Tips

Remember, some things have to end for better things to begin.

Back to Top ↑

2021

How to user fire extinguisher

Summary As you know, staff and your safety is paramount. So what if emergency take place, such as fire in office, how to help yourself and your colleagues by...

Deep dive into Kubernetes Client API

Summary To talk to K8s for getting data, there are few approaches. While K8s’ official Java library is the most widely used one. This blog will look into thi...

Whitelabel Error Page

Summary Whitelabel Error Page is the default error page in Spring Boot web app. It provide a more user-friently error page whenever there are any issues when...

Google maps no photos reviews

Summary I found a weird problem of the app Google Maps of my Oppo Android phone. That’s when you search a place in Google map, say “Central Park”, ideally th...

Debts in a nutshell

A debt security represents a debt owed by the issuer to an investor. Here, the investor acts as a lender to the issuer which may be a government, organisatio...

Back to Top ↑

2020

Debug Stuck IntelliJ

What happened to a debug job hanging in IntelliJ (IDEAS) IDE? You may find when you try to debug a class in Intellij but it stuck there and never proceed, e....

Awesome Kotlin

Difference with Scala Kotlin takes the best of Java and Scala, the response times are similar as working with Java natively, which is a considerable advantag...

JVM热身

此文是作者英文原文的翻译文章,英文原文在:http://todzhang.com/posts/2018-06-10-jvm-warm-up/

Mock in kotlin

Argument Matching & Answers For example, you have mocked DOC with call(arg: Int): Intfunction. You want to return 1 if argument is greater than 5 and -1 ...

Mock in kotlin

Argument Matching & Answers For example, you have mocked DOC with call(arg: Int): Intfunction. You want to return 1 if argument is greater than 5 and -1 ...

Curl

Linux Curl command

AOP

The concept of join points as matched by pointcut expressions is central to AOP, and Spring uses the AspectJ pointcut expression language by default.

Micrometer notes

As a general rule it should be possible to use the name as a pivot. Dimensions allow a particular named metric to be sliced to drill down and reason about th...

Awesome SSL certificates and HTTPS

What’s TLS TLS (Transport Layer Security) and its predecessor, SSL (Secure Sockets Layer), are security protocols designed to secure the communication betwee...

JVM warm up by Escape Analysis

Why JVM need warm up I don’t know how and why you get to this blog. But I know the key words in your mind are “warm” for JVM. As the name “warm up” suggested...

Java Concurrent

This blog is about noteworthy pivot points about Java Concurrent Framework Back to Java old days there were wait()/notify() which is error prone, while fr...

Back to Top ↑

2019

Conversations with God

Feelings is the language of the soul. If you want to know what’s true for you about something, look to how your’re feeling about.

Kafka In Spring

Enable Kafka listener annotated endpoints that are created under the covers by a AbstractListenerContainerFactory. To be used on Configuration classes as fol...

Mifid

FX Spot is not covered by the regulation, as it is not considered to be a financial instrument by ESMA, the European Union (EU) regulator. As FX is considere...

Foreign Exchange

currency pairs Direct ccy: means USD is part of currency pair Cross ccy: means ccy wihtout USD, so except NDF, the deal will be split to legs, both with...

Back to Top ↑

2018

Guice

A new type of Juice Put simply, Guice alleviates the need for factories and the use of new in your Java code. Think of Guice’s @Inject as the new new. You wi...

YAML

Key points All YAML files (regardless of their association with Ansible or not) can optionally begin with — and end with …. This is part of the YAML format a...

Sudo in a Nutshell

Sudo in a Nutshell Sudo (su “do”) allows a system administrator to give certain users (or groups of users) the ability to run some (or all) commands as root...

Zoo-keeper

ZK Motto the motto “ZooKeeper: Because Coordinating Distributed Systems is a Zoo.”

Cucumber

Acceptance testing vs unit test It’s sometimes said that unit tests ensure you build the thing right, whereas acceptance tests ensure you build the right thi...

akka framework of scala

philosophy The actor model adopts the philosophy that everything is an actor. This is similar to the everything is an object philosophy used by some object-o...

Apache Camel

Camel’s message model In Camel, there are two abstractions for modeling messages, both of which we’ll cover in this section. org.apache.camel.Message—The ...

JXM

Exporting your beans to JMX The core class in Spring’s JMX framework is the MBeanExporter. This class is responsible for taking your Spring beans and registe...

Solace MQ

Solace PubSub+ It is a message broker that lets you establish event-driven interactions between applications and microservices across hybrid cloud environmen...

Apigee

App deployment, configuration management and orchestration - all from one system. Ansible is powerful IT automation that you can learn quickly.

Ansible

Ansible: What Is It Good For? Ansible is often described as a configuration management tool, and is typically mentioned in the same breath as Chef, Puppet, a...

flexbox

How Flexbox works — explained with big, colorful, animated gifs

KDB

KDB However kdb+ evaluates expressions right-to-left. There are no precedence rules. The reason commonly given for this behaviour is that it is a much simple...

Agile and SCRUM

Key concept In Scrum, a team is cross functional, meaning everyone is needed to take a feature from idea to implementation.

Strategy-Of-Openshift-Releases

Release & Testing Strategy There are various methods for safely releasing changes to Production. Each team must select what is appropriate for their own ...

NodeJs Notes

commands to read files var lineReader = require(‘readline’).createInterface({ input: require(‘fs’).createReadStream(‘C:\dev\node\input\git_reset_files.tx...

CORS :Cross-Origin Resource Sharing

Cross-Origin Request Sharing - CORS (A.K.A. Cross-Domain AJAX request) is an issue that most web developers might encounter, according to Same-Origin-Policy,...

ngrx

Why @Effects? In a simple ngrx/store project without ngrx/effects there is really no good place to put your async calls. Suppose a user clicks on a button or...

iOS programming

View A view is also a responder (UIView is a subclass of UIResponder). This means that a view is subject to user interactions, such as taps and swipes. Thus,...

Back to Top ↑

2017

cloud computering

openshift vs openstack The shoft and direct answer is `OpenShift Origin can run on top of OpenStack. They are complementary projects that work well together....

cloud computering

Concepts Cloud computing is the on-demand demand delivery of compute database storage applications and other IT resources through a cloud services platform v...

Redux

whats @Effects You can almost think of your Effects as special kinds of reducer functions that are meant to be a place for you to put your async calls in suc...

reactive programing

The second advantage to a lazy subscription is that the observable doesn’t hold onto data by default. In the previous example, each event generated by the in...

Container

The Docker project was responsible for popularizing container development in Linux systems. The original project defined a command and service (both named do...

promise vs observiable

The drawback of using Promises is that they’re unable to handle data sources that produce more than one value, like mouse movements or sequences of bytes in ...

JDK source

interface RandomAccess Marker interface used by List implementations to indicate that they support fast (generally constant time) random access. The primary ...

SSH SFTP

Secure FTP SFTP over FTP is the equivalant of HTTPS over HTTP, the security version

AWS Tips

After establishing a SSH session, you can install a default web server by executing sudo yum install httpd -y. To start the web server, type sudo service htt...

Oracle

ORA-12899: Value Too Large for Column

Kindle notes

#《亿级流量网站架构核心技术》目录一览 TCP四层负载均衡 使用Hystrix实现隔离 基于Servlet3实现请求隔离 限流算法 令牌桶算法 漏桶算法 分布式限流 redis+lua实现 Nginx+Lua实现 使用sharding-jdbc分库分表 Disruptor+Redis...

Java Security Notes

Java Security well-behaved: programs should be prevent from consuming too much system resources

R Language

s<-read.csv("C:/Users/xxx/dev/R/IRS/SHH_SCHISHG.csv") # aggregate s2<-table(s$Original.CP) s3<-as.data.frame(s2) # extract by Frequency ordered s3...

SSH and Cryptography

SFTP versus FTPS SS: Secure Shell An increasing number of our customers are looking to move away from standard FTP for transferring data, so we are ofte...

Eclipse notes

How do I remove a plug-in? Run Help > About Eclipse > Installation Details, select the software you no longer want and click Uninstall. (On Macintosh i...

Maven-Notes

Maven philosophy “It is important to note that in the pom.xml file you specify the what and not the how. The pom.xml file can also serve as a documentatio...

Java New IO

Notes JDK 1.0 introduced rudimentary I/O facilities for accessing the file system (to create a directory, remove a file, or perform another task), accessi...

IT-Architect

SOA SOA is a set of design principles for building a suite of interoperable, flexible and reusable services based architecture. top-down and bottom-up a...

Algorithm

This page is about key points about Algorithm

Java-Tricky-Tech-Questions.md

What is the difference between Serializable and Externalizable in Java? In earlier version of Java, reflection was very slow, and so serializaing large ob...

Compare-In-Java

Concepts If you implement Comparable interface and override compareTo() method it must be consistent with equals() method i.e. for equal object by equals(...

Java Collections Misc

Difference between equals and deepEquals of Arrays in Java Arrays.equals() method does not compare recursively if an array contains another array on oth...

HashMap in JDK

Hashmap in JDK Some note worth points about hashmap Lookup process Step# 1: Quickly determine the bucket number in which this element may resid...

Java 8 Tips

This blog is listing key new features introduced in Java 8

Back to Top ↑

2016

Java GC notes

verbose:gc verbose:gc prints right after each gc collection and prints details about each generation memory details. Here is blog on how to read verbose gc

Hash Code Misc

contract of hashCode : Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consis...

Angulary Misc

Dependency Injection Angular doesn’t automatically know how you want to create instances of your services or the injector to create your service. You must co...

Java new features

JDK Versions JDK 1.5 in 2005 JDK 1.6 in 2006 JDK 1.7 in 2011 JDK 1.8 in 2014 Sun之前风光无限,但是在2010年1月27号被Oracle收购。 在被Oracle收购后对外承诺要回到每2年一个realse的节奏。但是20...

Simpler chronicle of CI(Continuous Integration) “乱弹系列”之持续集成工具

引言 有句话说有人的地方就有江湖,同样,有江湖的地方就有恩怨。在软件行业历史长河(虽然相对于其他行业来说,软件行业的历史实在太短了,但是确是充满了智慧的碰撞也是十分的精彩)中有一些恩怨情愁,分分合合的小故事,比如类似的有,从一套代码发展出来后面由于合同到期就分道扬镳,然后各自发展成独门产品的Sybase DB和微...

浅谈软件单元测试中的“断言” (assert),从石器时代进步到黄金时代。

大家都知道,在软件测试特别是在单元测试时,必用的一个功能就是“断言”(Assert),可能有些人觉得不就一个Assert语句,没啥花头,也有很多人用起来也是懵懵懂懂,认为只要是Assert开头的方法,拿过来就用。一个偶然的机会跟人聊到此功能,觉得还是有必要在此整理一下如何使用以及对“断言”的理解。希望可以帮助大家...

Kubernetes 与 Docker Swarm的对比

Kubernetes 和Docker Swarm 可能是使用最广泛的工具,用于在集群环境中部署容器。但是这两个工具还是有很大的差别。

http methods

RFC origion http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.2)

Spark-vs-Storm

The stark difference among Spark and Storm. Although both are claimed to process the streaming data in real time. But Spark processes it as micro-batches; wh...

微服务

可以想像一下,之前的传统应用系统,像是一个大办公室里面,有各个部门,销售部,采购部,财务部。办一件事情效率比较高。但是也有一些弊端,首先,各部门都在一个房间里。

kibana, view layer of elasticsearch

What’s Kibana kibana is an open source data visualization plugin for Elasticsearch. It provides visualization capabilities on top of the content indexed on...

kibana, view layer of elasticsearch

What’s Kibana kibana is an open source data visualization plugin for Elasticsearch. It provides visualization capabilities on top of the content indexed on...

iConnect

UI HTML5, AngularJS, BootStrap, REST API, JSON Backend Hadoop core (HDFS), Hive, HBase, MapReduce, Oozie, Pig, Solr

Data Structure

Binary Tree A binary tree is a tree in which no node can have more than two children. A property of a binary tree that is sometimes important is that th...

Something about authentication

It’s annoying to keep on repeating typing same login and password when you access multiple systems within office or for systems in external Internet. There a...

SQL

Differences between not in, not exists , and left join with null

Github page commands notes

404 error for customized domain (such as godday) 404 There is not a GitHub Pages site here. Go to github master branch for gitpages site, manually add CN...

RenMinBi International

RQFII RQFII stands for Renminbi Qualified Foreign Institutional Investor. RQFII was introduced in 2011 to allow qualified foreign institutional investors to ...

Load Balancing

Concepts LVS means Linux Virtual Server, which is one Linux built-in component.

Python

(‘—–Unexpected error:’, <type ‘exceptions.TypeError’>) datetime.datetime.now()

Microservices vs. SOA

Microservice Services are organized around capabilities, e.g., user interface front-end, recommendation, logistics, billing, etc. Services are small in ...

Java Class Loader

Codecache The maximum size of the code cache is set via the -XX:ReservedCodeCacheSize=N flag (where N is the default just mentioned for the particular com...

Back to Top ↑