Hot answers tagged

125 votes

Why use Optional in Java 8+ instead of traditional null pointer checks?

Style 2 isn't going Java 8 enough to see the full benefit. You don't want the if ... use at all. See Oracle's examples. Taking their advice, we get: Style 3 // Changed EmployeeServive to return an ...
Caleth's user avatar
  • 10.5k
50 votes
Accepted

Why should I use "functional operations" instead of a for loop?

Streams provide much better abstraction for composition of different operations you want to do on top of collections or streams of data coming in. Especially when you need to map elements, filter and ...
luboskrnac's user avatar
50 votes

Why use Optional in Java 8+ instead of traditional null pointer checks?

If you're using Optional as a "compatibility" layer between an older API that may still return null, it may be helpful to create the (non-empty) Optional at the latest stage that you're sure that you ...
Joshua Taylor's user avatar
24 votes

Why use Optional in Java 8+ instead of traditional null pointer checks?

There is next to no added value in having an Optional of a single value. As you've seen, that just replaces a check for null with a check for presence. There is huge added value in having a ...
Kilian Foth's user avatar
23 votes

Why is using an optional preferential to null-checking the variable?

An Optional brings stronger typing into operations that may fail, as the other answers have covered, but that is far from the most interesting or valuable thing Optionals bring to the table. Much ...
Karl Bielefeldt's user avatar
22 votes
Accepted

Why is using an optional preferential to null-checking the variable?

Optional harnesses the type system for doing work that you'd otherwise have to do all in your head: remembering whether or not a given reference may be null. This is good. It's always smart to let the ...
Kilian Foth's user avatar
20 votes

Why use Optional in Java 8+ instead of traditional null pointer checks?

As long as you use Optional just like a fancy API for isNotNull(), then yes, you won't find any differences with just checking for null. Things you should NOT use Optional for Using Optional just to ...
walen's user avatar
  • 355
18 votes
Accepted

Is there a performance benefit to using the method reference syntax instead of lambda syntax in Java 8?

In many scenarios, I think lambda and method-reference is equivalent. But the lambda will wrap the invocation target by the declaring interface type. For example public class InvokeTest { ...
JasonMing's user avatar
  • 296
18 votes

Why should I use "functional operations" instead of a for loop?

Another advantage of using the functional streaming API is, that it hides implementation details. It only describes what should be done, not how. This advantage becomes obvious when looking at the ...
Stefan Dollase's user avatar
17 votes

Parse both en_US and en-US as locale in Java

Rather than replacing without understanding I'd like to explain why there appear to be two forms one underscored and another hyphened and why one should care. tl;dr it is not simple as a single char ...
bric3's user avatar
  • 271
15 votes

Why should I use "functional operations" instead of a for loop?

If anything, it is harder to read and understand. That is highly subjective. I find the second version much easier to read and understand. It matches how other languages (e.g. Ruby, Smalltalk, ...
Jörg W Mittag's user avatar
15 votes

Why is Optional.get() without calling isPresent() bad, but not iterator.next()?

The Optional class is intended to be used when it is not known whether or not the item it contains is present. The warning exists to notify programmers that there is an additional possible code path ...
Jules's user avatar
  • 17.6k
13 votes
Accepted

Why is Optional.get() without calling isPresent() bad, but not iterator.next()?

First of all, consider that the check is complex and probably relatively time consuming to do. It requires some static analysis, and there might be quite a bit of code between the two calls. Second, ...
Karl Bielefeldt's user avatar
13 votes

How does sorting with java 8 stream work under the hood?

You can use grepcode.com to search through the Java standard library code (and some other libraries). Unfortunately, the stream implementation code is rather abstract. A good starting point is the ...
amon's user avatar
  • 133k
13 votes
Accepted

The use (or abuse) of Java 8, Mapper function

If you actually mean something like public <S super Company, T> Optional<T> getCompany(int companyId, Mapper<S,T> mapper) and the only function of the mapper is to transform the ...
Dr. Hans-Peter Störr's user avatar
12 votes

Why use Optional in Java 8+ instead of traditional null pointer checks?

The key point for me in using Optional is keep clear when developer need check if function return value or not. //service 1 Optional<Employee> employeeOptional = employeeService.getEmployee(); ...
Rodrigo Menezes's user avatar
11 votes
Accepted

Why does java.time have methods for creating objects instead of just constructors?

Factory methods allow simplifying the constructors - the difference which instance in time is represented by the Object can be separated from the calculation of the instant. There are lots of factory ...
Hulk's user avatar
  • 508
10 votes

Why is using an optional preferential to null-checking the variable?

It highlights the possibility of null as a valid response, which people often assume (rightly or wrongly) is not going to be returned. Highlighting the few times when null is valid allows omitting ...
Richard Tingle's user avatar
10 votes
Accepted

What's the complexity of Java's string split function?

The complexity will depend on the regex that you use to do the splitting. (Yes, the argument you supply to String.split(...) is a regex!) For your example, it will be O(N) where N is the number of ...
Stephen C's user avatar
  • 25.2k
8 votes

Why does java.time have methods for creating objects instead of just constructors?

It's not always necessary to create a new object when obtaining a value of an immutable type. A factory method may return an object that has already been created while a constructor call always ...
COME FROM's user avatar
  • 2,666
8 votes

Why use Optional in Java 8+ instead of traditional null pointer checks?

Your main mistake is that you're still thinking in more procedural terms. This is not meant as a criticism of you as a person, it's merely an observation. Thinking in more functional terms comes with ...
Haakon Løtveit's user avatar
8 votes
Accepted

Database agnostic DAO (NoSQL + SQL)

The best way to guarantee that you stay reasonably decoupled from the database, but at the same time remain free to use any feature of it, is to not create an abstraction layer for the database. (Well,...
Robert Bräutigam's user avatar
7 votes
Accepted

Java8: why two composition methods: andThen and compose?

compose is a traditional operation. Its order was decided by mathematicians. However, like a lot of things originally decided by mathematicians, the order isn't a very convenient convention for ...
Karl Bielefeldt's user avatar
7 votes
Accepted

When should I create my own @FunctionalInterface rather than reuse the interfaces defined in java.util.function?

First off this is largely a matter of style and API design, because callers can always convert from one equivalent functional interface to another via method references. So if you have a Consumer<T&...
dimo414's user avatar
  • 393
6 votes
Accepted

Should Java 8 Stream instances always be close()'d?

As you said, in Java you need to know exactly who is responsible for freeing which resource, so you can put in the appropriate try-catch-constructs, try-with-resources or somehow delegate that task. ...
Deduplicator's user avatar
  • 8,601
6 votes

Why is Optional.get() without calling isPresent() bad, but not iterator.next()?

I agree that there is no inherent difference in these, however, I'd like to point out a bigger flaw. In both cases, you have a type, which provides a method that is not guaranteed to work and you are ...
Frank's user avatar
  • 14.4k
6 votes
Accepted

Parsing Multiple Files and Their Contents in Java using Multithreading without ExecutorService

Great question! I've written a small example (it only uses 6 threads, but can easily be expanded) to illustrate how you could read multiple files (one thread to read each file) and process the data ...
D.B.'s user avatar
  • 176
5 votes
Accepted

Supporting Multiple Java Versions in OSS Libraries

What benefits brings Java-9 over your current Java-8 version ? I mean to the person using your library. Deploying two concurrent version of the same library has a LOT of downsides. Do you need to ...
Newtopian's user avatar
  • 7,211
5 votes

Should Java 8 Stream instances always be close()'d?

As far as "best practices" goes, I think it's a good idea to use a naming convention for methods that return "resource streams". If a stream has to be close()ed, call the factory method open() or ...
Jason Trump's user avatar

Only top scored, non community-wiki answers of a minimum length are eligible