Questions tagged [java-8]

Use this tag for questions specific to Java 8 which is version 8 (internal number 1.8) of the Java platform, released on 18 March 2014. In most cases, you should also specify the java tag.

java-8
Filter by
Sorted by
Tagged with
683 votes
35 answers
582k views

Java 8 Distinct by property

In Java 8 how can I filter a collection using the Stream API by checking the distinctness of a property of each object? For example I have a list of Person object and I want to remove people with the ...
RichK's user avatar
  • 11.6k
1145 votes
17 answers
496k views

:: (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 ...
Narendra Pathai's user avatar
21 votes
1 answer
12k views

javafx 8 compatibility issues - FXML static fields or methods

I have designed a javafx application which works fine in jdk 7. When I try to run it in java 8 I am getting the below exceptions: javafx.fxml.LoadException: at javafx.fxml.FXMLLoader....
Christopher_Daniel's user avatar
360 votes
14 answers
161k views

Uses for Optional

Having been using Java 8 now for 6+ months or so, I'm pretty happy with the new API changes. One area I'm still not confident in is when to use Optional. I seem to swing between wanting to use it ...
Will's user avatar
  • 6,611
173 votes
14 answers
107k views

Zipping streams using JDK8 with lambda (java.util.stream.Streams.zip)

In JDK 8 with lambda b93 there was a class java.util.stream.Streams.zip in b93 which could be used to zip streams (this is illustrated in the tutorial Exploring Java8 Lambdas. Part 1 by Dhananjay Nene)...
artella's user avatar
  • 5,108
219 votes
19 answers
97k views

Limit a stream by a predicate

Is there a Java 8 stream operation that limits a (potentially infinite) Stream until the first element fails to match a predicate? In Java 9 we can use takeWhile as in the example below to print all ...
MForster's user avatar
  • 9,316
559 votes
5 answers
264k views

What's the difference between Instant and LocalDateTime?

I know that: Instant is rather a "technical" timestamp representation (nanoseconds) for computing. LocalDateTime is rather date/clock representation including time-zones for humans. Still ...
manuel aldana's user avatar
635 votes
28 answers
297k views

Is it possible to use Java 8 for Android development?

Searching the web, it is not clear if Java 8 is supported for Android development or not. Before I download/setup Java 8, can some one point me at any "official" documentation that says Java 8 is or ...
nPn's user avatar
  • 16.5k
495 votes
12 answers
963k views

How can I parse/format dates with LocalDateTime? (Java 8)

Java 8 added a new java.time API for working with dates and times (JSR 310). I have date and time as string (e.g., "2014-04-08 12:30"). How can I obtain a LocalDateTime instance from the ...
micha's user avatar
  • 48.9k
489 votes
16 answers
290k views

Custom thread pool in Java 8 parallel stream

Is it possible to specify a custom thread pool for Java 8 parallel stream? I can not find it anywhere. Imagine that I have a server application and I would like to use parallel streams. But the ...
Lukas's user avatar
  • 13.9k
390 votes
15 answers
207k views

Difference between final and effectively final

I'm playing with lambdas in Java 8 and I came across warning local variables referenced from a lambda expression must be final or effectively final. I know that when I use variables inside anonymous ...
alex's user avatar
  • 11.2k
640 votes
28 answers
516k views

Java 8 Lambda function that throws exception?

I know how to create a reference to a method that has a String parameter and returns an int, it's: Function<String, Integer> However, this doesn't work if the function throws an exception, say ...
Rocky Pulley's user avatar
221 votes
3 answers
48k views

Does a lambda expression create an object on the heap every time it's executed?

When I iterate over a collection using the new syntactic sugar of Java 8, such as myStream.forEach(item -> { // do something useful }); Isn't this equivalent to the 'old syntax' snippet below? ...
Bastian Voigt's user avatar
530 votes
27 answers
447k views

Is there a concise way to iterate over a stream with indices in Java 8?

Is there a concise way to iterate over a stream whilst having access to the index in the stream? String[] names = {"Sam","Pamela", "Dave", "Pascal", "Erik"}; List<String> nameList; Stream<...
Graeme Moss's user avatar
  • 8,213
1058 votes
23 answers
763k views

Java 8 List<V> into Map<K, V>

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> ...
Tom's user avatar
  • 16k
372 votes
7 answers
104k views

Should Java 8 getters return optional type?

Optional type introduced in Java 8 is a new thing for many developers. Is a getter method returning Optional<Foo> type in place of the classic Foo a good practice? Assume that the value can be ...
leonprou's user avatar
  • 4,748
656 votes
6 answers
242k views

Should I always use a parallel stream when possible?

With Java 8 and lambdas it's easy to iterate over collections as streams, and just as easy to use a parallel stream. Two examples from the docs, the second one using parallelStream: ...
Matsemann's user avatar
  • 21.4k
220 votes
10 answers
105k views

In Java streams is peek really only for debugging?

I'm reading up about Java streams and discovering new things as I go along. One of the new things I found was the peek() function. Almost everything I've read on peek says it should be used to debug ...
Adam.J's user avatar
  • 2,579
843 votes
12 answers
694k views

How can I turn a List of Lists into a List in Java 8?

If I have a List<List<Object>>, how can I turn that into a List<Object> that contains all the objects in the same iteration order by using the features of Java 8?
Sarah Szabo's user avatar
  • 10.6k
116 votes
3 answers
42k views

Why in Java 8 split sometimes removes empty strings at start of result array?

Before Java 8 when we split on empty string like String[] tokens = "abc".split(""); split mechanism would split in places marked with | |a|b|c| because empty space "" ...
Pshemo's user avatar
  • 124k
31 votes
3 answers
5k views

finalize() called on strongly reachable objects in Java 8

We recently upgraded our message processing application from Java 7 to Java 8. Since the upgrade, we get an occasional exception that a stream has been closed while it is being read from. Logging ...
Nathan's user avatar
  • 1,448
190 votes
12 answers
154k views

What are functional interfaces used for in Java 8?

I came across a new term in Java 8: "functional interface". I could only find one use of it while working with lambda expressions. Java 8 provides some built-in functional interfaces and if ...
Madhusudan's user avatar
  • 4,705
82 votes
8 answers
11k views

Why filter() after flatMap() is "not completely" lazy in Java streams?

I have the following sample code: System.out.println( "Result: " + Stream.of(1, 2, 3) .filter(i -> { System.out.println(i); ...
Vadym S. Khondar's user avatar
51 votes
9 answers
34k views

How to force max to return ALL maximum values in a Java Stream?

I've tested a bit the max function on Java 8 lambdas and streams, and it seems that in case max is executed, even if more than one object compares to 0, it returns an arbitrary element within the tied ...
Whimusical's user avatar
  • 6,501
634 votes
16 answers
166k views

When to use: Java 8+ interface default method, vs. abstract method

Java 8 allows for default implementation of methods in interfaces called Default Methods. I am confused between when would I use that sort of interface default method, instead of an abstract class (...
Narendra Pathai's user avatar
175 votes
6 answers
57k views

How to serialize a lambda?

How can I elegantly serialize a lambda? For example, the code below throws a NotSerializableException. How can I fix it without creating a SerializableRunnable "dummy" interface? public static void ...
assylias's user avatar
  • 325k
374 votes
18 answers
163k views

How can I throw checked exceptions from inside Java 8 lambdas/streams?

How can I throw checked exceptions from inside Java 8 lambda, used in a stream for example? In other words, I want to make code like this compile: public List<Class> getClasses() throws ...
Marcelo Glasberg's user avatar
614 votes
14 answers
630k views

Convert java.util.Date to java.time.LocalDate

What is the best way to convert a java.util.Date object to the new JDK 8/JSR-310 java.time.LocalDate? Date input = new Date(); LocalDate date = ???
JodaStephen's user avatar
  • 62.3k
394 votes
12 answers
496k views

Java 8: Difference between two LocalDateTime in multiple units

I am trying to calculate the difference between two LocalDateTime. The output needs to be of the format y years m months d days h hours m minutes s seconds. Here is what I have written: import java....
Tapas Bose's user avatar
  • 29.3k
656 votes
26 answers
320k views

Why should Java 8's Optional not be used in arguments

I've read on many Web sites Optional should be used as a return type only, and not used in method arguments. I'm struggling to find a logical reason why. For example I have a piece of logic which ...
Neil Stevens's user avatar
  • 6,985
211 votes
2 answers
164k views

How to ensure order of processing in Java 8 streams?

I want to process lists inside an XML Java object. I have to ensure processing all elements in the order I received them. Should I therefore call sequential on each stream I use? list.stream()....
membersound's user avatar
  • 84.1k
155 votes
4 answers
38k views

Comparator.reversed() does not compile using lambda

I have a list with some User objects and i'm trying to sort the list, but only works using method reference, with lambda expression the compiler gives an error: List<User> userList = Arrays....
Andrey's user avatar
  • 2,545
121 votes
23 answers
93k views

Collect successive pairs from a stream

Given an object or primitive stream such as { 0, 1, 2, 3, 4 }, how can I most elegantly transform it into given form (assuming, of course, I've defined class Pair)? { new Pair(0, 1), new Pair(1, 2), ...
Aleksandr Dubinsky's user avatar
59 votes
2 answers
18k views

How will Java lambda functions be compiled?

Loop.times(5, () -> { System.out.println("looping"); }); Which of these would it effectively compile to? for(int i = 0; i < 5; i++) System.out.println("looping"); or something like ...
rtheunissen's user avatar
  • 7,397
555 votes
8 answers
508k views

Java 8 Iterable.forEach() vs foreach loop

Which of the following is better practice in Java 8? Java 8: joins.forEach(join -> mIrc.join(mSession, join)); Java 7: for (String join : joins) { mIrc.join(mSession, join); } I have lots ...
nebkat's user avatar
  • 8,515
141 votes
9 answers
259k views

Group by multiple field names in java 8

I found the code for grouping the objects by some field name from POJO. Below is the code for that: public class Temp { static class Person { private String name; private int ...
Mital Pritmani's user avatar
37 votes
5 answers
78k views

Removal of JDBC ODBC bridge in java 8

Starting with Java 8, the JDBC-ODBC Bridge will no longer be included with the JDK. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // classNotFoundException is thrown Is there any other solution ...
Karthik's user avatar
  • 1,152
275 votes
6 answers
433k views

What does the arrow operator, '->', do in Java?

While hunting through some code I came across the arrow operator, what exactly does it do? I thought Java did not have an arrow operator. return (Collection<Car>) CollectionUtils.select(...
Rylander's user avatar
  • 19.9k
113 votes
4 answers
40k views

Very confused by Java 8 Comparator type inference

I've been looking at the difference between Collections.sort and list.sort, specifically regarding using the Comparator static methods and whether param types are required in the lambda expressions. ...
Tranquility's user avatar
  • 3,161
27 votes
2 answers
6k views

Why does a Java method reference with return type match the Consumer interface?

I am confused by the following code class LambdaTest { public static void main(String[] args) { Consumer<String> lambda1 = s -> {}; Function<String, String> ...
Ulrich Schmidt's user avatar
514 votes
8 answers
162k views

Convert Iterable to Stream using Java 8 JDK

I have an interface which returns java.lang.Iterable<T>. I would like to manipulate that result using the Java 8 Stream API. However Iterable can't "stream". Any idea how to use the Iterable ...
rayman's user avatar
  • 21.2k
154 votes
17 answers
305k views

JSON Java 8 LocalDateTime format in Spring Boot

I'm having a small problem with formatting a Java 8 LocalDateTime in my Spring Boot Application. With 'normal' dates I have no problem, but the LocalDateTime fields are converted to the following: "...
Erik Pragt's user avatar
  • 14.2k
86 votes
3 answers
17k views

Is method reference caching a good idea in Java 8?

Consider I have code like the following: class Foo { Y func(X x) {...} void doSomethingWithAFunc(Function<X,Y> f){...} void hotFunction(){ doSomethingWithAFunc(this::func); ...
gexicide's user avatar
  • 39.2k
15 votes
5 answers
22k views

Error when using LogManager (l4j2) with Java 8 (java.lang.reflect.AnnotatedElement cannot be resolved)

I just encountered a strange error when switching the JDK version of a new Project of mine from 7u45 to 8u20. A harmless LogManager declaration at the beginning of my class is being refused with the ...
Corsair's user avatar
  • 1,044
975 votes
21 answers
634k views

What's the difference between map() and flatMap() methods in Java 8?

In Java 8, what's the difference between Stream.map() and Stream.flatMap() methods?
cassiomolin's user avatar
354 votes
7 answers
108k views

Explicitly calling a default method in Java

Java 8 introduces default methods to provide the ability to extend interfaces without the need to modify existing implementations. I wonder if it's possible to explicitly invoke the default ...
GOTO 0's user avatar
  • 45.1k
244 votes
6 answers
202k views

PermGen elimination in JDK 8

I have installed JDK 8 and trying to run Eclipse. I am getting following warning message: Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=512m; support was removed in 8.0 ...
Shamim Ahmmed's user avatar
624 votes
9 answers
669k views

Converting between java.time.LocalDateTime and java.util.Date

Java 8 has a completely new API for date and time. One of the most useful classes in this API is LocalDateTime, for holding a timezone-independent date-with-time value. There are probably millions ...
Knut Arne Vedaa's user avatar
36 votes
3 answers
36k views

Getting the date from a ResultSet for use with java.time classes

Is there anyway to get a java.time (new in Java 8) compatible time class out of a ResultSet? I am aware you can use ResultSet's getDate or getTimestamp but these method return java.sql.Date / java....
Thomas Paulin's user avatar
253 votes
6 answers
220k views

How can I count occurrences with groupBy?

I want to collect the items in a stream into a map which groups equal objects together, and maps to the number of occurrences. List<String> list = Arrays.asList("Hello", "Hello&...
Muhammad Hewedy's user avatar

1
2 3 4 5
75