How to convert a Java 8 Stream to an Array?

What is the easiest/shortest way to convert a Java 8 Stream into an array? 10 s 10 The easiest method is to use the toArray(IntFunction<A[]> generator) method with an array constructor reference. This is suggested in the API documentation for the method. String[] stringArray = stringStream.toArray(String[]::new); What it does is find a method that takes … Read more

Java 8 List into Map

I want to translate a List of objects into a Map using Java 8’s streams and lambdas. This is how I would write it in Java 7 and below. private Map<String, Choice> nameMap(List<Choice> choices) { final Map<String, Choice> hashMap = new HashMap<>(); for (final Choice choice : choices) { hashMap.put(choice.getName(), choice); } return hashMap; } … Read more

:: (double colon) operator in Java 8

I was exploring the Java 8 source and found this particular part of code very surprising: //defined in IntPipeline.java @Override public final OptionalInt reduce(IntBinaryOperator op) { return evaluate(ReduceOps.makeInt(op)); } @Override public final OptionalInt max() { return reduce(Math::max); //this is the gotcha line } //defined in Math.java public static int max(int a, int b) { return … Read more

typeof in Java 8

You can use the getClass() method to get the type of the object you are using: Object obj = null; obj = new ArrayList<String>(); System.out.println(obj.getClass()); obj = “dummy”; System.out.println(obj.getClass()); obj = 4; System.out.println(obj.getClass()); This will generate the following output: class java.util.ArrayList class java.lang.String class java.lang.Integer As you see it will show the type of the object which … Read more

:: (double colon) operator in Java 8

Usually, one would call the reduce method using Math.max(int, int) as follows: reduce(new IntBinaryOperator() { int applyAsInt(int left, int right) { return Math.max(left, right); } }); That requires a lot of syntax for just calling Math.max. That’s where lambda expressions come into play. Since Java 8 it is allowed to do the same thing in a much shorter way: reduce((int … Read more

LocalDate to java.util.Date and vice versa simplest conversion?

Is there a simple way to convert a LocalDate (introduced with Java 8) to java.util.Date object? By ‘simple’, I mean simpler than this Nope. You did it properly, and as concisely as possible. java.util.Date.from( // Convert from modern java.time class to troublesome old legacy class. DO NOT DO THIS unless you must, to inter operate … Read more