Avoid NoSuchElementException with Stream - java

I have the following Stream:
Stream<T> stream = stream();
T result = stream.filter(t -> {
double x = getX(t);
double y = getY(t);
return (x == tx && y == ty);
}).findFirst().get();
return result;
However, there is not always a result which gives me the following error:
NoSuchElementException: No value present
So how can I return a null if there is no value present?

You can use Optional.orElse, it's much simpler than checking isPresent:
T result = stream.filter(t -> {
double x = getX(t);
double y = getY(t);
return (x == tx && y == ty);
}).findFirst().orElse(null);
return result;

Stream#findFirst() returns an Optional which exists specifically so that you don't need to operate on null values.
A container object which may or may not contain a non-null value. If a
value is present, isPresent() will return true and get() will return
the value.
Otherwise, Optional#get() throws a NoSuchElementException.
If a value is present in this Optional, returns the value, otherwise
throws NoSuchElementException.
An Optional will never expose its value if it is null.
If you really have to, just check isPresent() and return null yourself.
Stream<T> stream = stream();
Optional<T> result = stream.filter(t -> {
double x = getX(t);
double y = getY(t);
return (x == tx && y == ty);
}).findFirst();
if (result.isPresent())
return result.get();
return null;

An alternate method for replacing the Optional.get (which more likely than not fails the user's intentions with a NoSuchElementException) is with a more verbose API introduced in JDK10 termed as Optional.orElseThrow(). In author's words -
Optional.get() is an "attractive nuisance" and is too tempting for
programmers, leading to frequent errors. People don't expect a getter
to throw an exception. A replacement API for Optional.get() with
equivalent semantics should be added.
Note :- The underlying implementation of both these APIs is same, yet the latter reads out more clearly that a NoSuchElementException would be thrown by default if the value is not present which inlines to the existing Optional.orElseThrow​(Supplier<? extends X> exceptionSupplier) implementation used by consumers as an explicit alternate.

If you wish to continue using the object and not throw any exception, then
Optional.isPresent(object)
is the way to go

Related

Java Optional if object is not null - returns the method result, if null - returns default value

Is it possible to transform this code to a Java 8 Optional one-line expression?
long lastPollTime;
if (object != null) {
lastPollTime = object.getTime();
} else {
lastPollTime = 0;
}
i.e. if some object is not null, I need to call an object method and return its result, or else return 0.
Optional.ofNullable().orElse() is not suitable, as it returns the object of the same type, but i need the result of the method call or some default value.
A few forms:
long lastPollTime = Optional.ofNullable(object).map(o -> o.getTime()).orElse(0L);
long lastPollTime = Optional.ofNullable(object).map(YouObjectClass::getTime).orElse(0L);
long lastPollTime = Optional.ofNullable(object).isPresent() ? object.getTime() : 0;
long lastPollTime = object != null ? object.getTime() : 0;
Of these, the last one, which doesn't use Optional (and therefore doesn't strictly answer your question!) is simpler to read and has fewer runtime overheads, and so should be preferred.
Arguably, it's even simpler if you reverse the options:
long lastPollTime = object == null ? 0 : object.getTime();
... although you might prefer to have the default last -- it's a matter of personal taste.
If you really can't use ternary operators, and you're doing this a lot, you could write your own utility method:
public <T,U> U mapWithFallback(T obj, Function<T,U> function, U fallback) {
if(obj == null) {
return fallback;
} else {
return function.apply(obj);
}
}
... callable as:
long lastPollTime = mapWithFallback(object, o -> o.getTime(), 0);
... or make a complete mockery of your no-ternaries check using:
public <T,U> U ifElse( Supplier<Boolean> a, Supplier<U> ifTrue, Supplier<U> ifFalse) {
if(a.get()) {
return ifTrue.get();
} else {
return ifFalse.get();
}
}
long lastPollTime = ifElse( () -> object == null, () -> object.getTime(), () -> 0);
It's in even better taste to avoid null references altogether, so that this kind of check isn't needed -- for example using the Null Object pattern.
... or by writing methods that return Optional rather than potential nulls. Optional is a great class; use it. Just don't convert something to Optional purely so you can immediately check whether it's empty.
long lastPollTime = Optional.ofNullable(object).map(YouObjectClass::getTime).orElse(0L);
long lastPollTime = Optional.ofNullable(object).map(o -> o.getTime()).orElse(0L);
Instead of o -> o.getTime() you could use a methods reference like ClassOfObject::getTime
long lastPollTime = object != null ?object.getTime():0;
you can do like below with java 8
long lastPollTime=Optional.ofNullable(object).isPresent()?object.getTime():0;
or without using java8 like this
long lastPollTime = object != null ?object.getTime():0;
Re ternary vs optional, if you ever needed to nest them the optional ends up being easier to read
long lastPollTime = Optional.ofNullable(object1)
.map(o -> o.getTime())
.orElse(Optional.ofNullable(object2)
.map(o -> o.getTime())
.orElse(0));

checking and setting variable, efficiently

I am new to programming and have a simple question: is there a "better" or more efficient way of doing this...
if (x != 0) {
y = x;
}
or
if (getMethod() != null) {
value = getMethod();
}
I'm new to programming and above code (esp the 2nd one) seems inefficient.
Thanks in advance.
You second example can suffer from a "Time of check, to time of use" weakness. If the first invocation of getMethod() returns non-null, it is possible that your second invocation will return null. A better way to do it would be:
value = getMethod();
if(NULL != value)
{
/* use value as planned */
}
else
{
/* handle a null value, probably an error */
}
if interested, you can read more about TOCTTOU weaknesses here.
For your first example, I don't really see a better way of doing this.
N.B. This answer is from the perspective of a C programmer (seeing as how C was one of your tags).
Hope this helps
- T.
You can make it shorter
if ( x ) y = x;
is the same as
if (x != 0) {
y = x;
}
And
if ( getMethod() ) value = getMethod();
is the same as
if (getMethod() != null) {
value = getMethod();
}
First code snippet:
In C any non-zero value is treated as true and 0 treated as false. So, for the first example, you can rewrite it as:
if (x) {
y = x; // this line will be executed if x not equal to zero
}
Second code snippet:
You called getMethod() twice which is not efficient. As per your code, you are assigning the return value of getMethod() into value if getMethod() returns anything but NULL. So you can use a temporary variable to check the return value of getMethod(), like following:
temp = getMethod();
if (temp != null) {
value = temp;
}
That will reduce calling same method twice.

Is there a way to create an AND/OR/ETC. Boolean statement that is comparing with the same value without redefining the value? [duplicate]

This question already has answers here:
Best way to format multiple 'or' conditions in an if statement
(8 answers)
Closed 1 year ago.
Basically, what I want to do is check two integers against a given value, therefore, classically what you would do is something like this:
//just to get some values to check
int a, b;
a = (int)(Math.random()*5);
b = (int)(Math.random()*5);
//the actual thing in question
if(a == 0 || b == 0)
{
//Then do something
}
But is there a more concise format to do this? Possibly similar to this (which returns a bad operand type):
//just to get some values to check
int a, b;
a = (int)(Math.random()*5);
b = (int)(Math.random()*5);
//the actual thing in question
if((a||b) == 0)
{
//Then do something
}
You can do the following in plain java
Arrays.asList(a, b, c, d).contains(x);
Unfortunately there is no such construct in Java.
It this kind of comparison is frequent in your code, you can implement a small function that will perform the check for you:
public boolean oneOfEquals(int a, int b, int expected) {
return (a == expected) || (b == expected);
}
Then you could use it like this:
if(oneOfEquals(a, b, 0)) {
// ...
}
If you don't want to restrict yourselft to integers, you can make the above function generic:
public <T> boolean oneOfEquals(T a, T b, T expected) {
return a.equals(expected) || b.equals(expected);
}
Note that in this case Java runtime will perform automatic boxing and unboxing for primitive types (like int), which is a performance loss.
As referenced from this answer:
In Java 8+, you might use a Stream and anyMatch. Something like
if (Stream.of(b, c, d).anyMatch(x -> x.equals(a))) {
// ... do something ...
}
Note that this has the chance of running slower than the other if checks, due to the overhead of wrapping these elements into a stream to begin with.
I think that a bit-wise OR:
if ((a | b) == 0) . . .
would work if you want to check specifically for 0. I'm not sure if this saves any execution time. More to the point, it makes for cryptic code, which will make the future maintainer of this code curse you (even if its yourself). I recommend sticking with the more-typing option.
Bah. I misread OP's original logic.
Another go...
If you want to test whether any one of many variables is equal to an expected value, a generic function might work:
public <T> boolean exists(T target, T... values) {
for (T value : values) {
if (target == null) {
if (value == null) {
return true;
}
} else if (target.equals(value)) {
return true;
}
}
return false;
}
This will work for any number of objects of one type. Primitives will be autoboxed so it will work with them as well. Your original code will be something like:
if (test(0, a, b)) {
// do something
}
(A better method name would be desperately needed to even consider whether this an improvement over what you have now. Even if the test expands to 3 or 4 variables, I question the need for this kind of thing.) Note that this also works with arrays:
int[] values = { . . . };
if (test(0, values)) { . . .
and it can be used to test whether an array (or any of a collection of variables) is null.
if(a == 0 || b == 0)
{
//Then do something
}
Why not keep it readable? What is not concise about this? On the other hand,
a = (int)(Math.random()*5);
involves an unnecessary cast. Why not just use Random and invoke nextInt()?
For this example, you can do
if (a * b == 0)
or for more variables
if (a * b * c * d == 0)
while more concise it may not be as clear. For larger values, you need to cast to a long to avoid an overflow.
You could put the integers in a set and see if it contains the given value. Using Guava:
if(newHashSet(a, b).contains(0)){
// do something
}
But two simple int comparisons are probably easier to understand in this case.
Here's a modification of #buc's answer that can take any number of any arguments:
public <T> boolean oneOfEquals(T expected, T... os) {
for (T o : os) {
if (expected.equals(o)) return true;
}
return false;
}
Even if you have used the bit-wise operation as Ted suggested, the expressions are not equal, since one requires at least one of the variables to be zero and the second requires both of them to be zero.
Regarding your question, there is no such shortcut in Java.
You can try this code:
public static boolean match (Object ref, Object... objects)
{
if (ref == null)
return false;
//
for (Object obj : objects)
if (obj.equals (ref))
return true;
//
return false;
} // match
So if you can check this way:
if (match (reference, "123", "124", "125"))
; // do something
In Java 8 we can achieve the same by using the below method:
private boolean methodName(int variant,int... args){
if(args.length > 0){ return Arrays.stream(args).anyMatch( x -> x == variant); }
return false;
}
The given method will return true if the variant will match any possible input(s). This is used for or condition.
In the same way, if you want to do &&(and) condition then you just need to used other Java 8 methods:
Note: These methods take Predicate as an argument.
anyMatch: return true the moment the first predicate returns true otherwise false.
allMatch: return true if all the predicates return true otherwise false.
noneMatch: return true if none of the predicates return true otherwise false.
Performance Note: This is good when you have enough amount of data to
check as it has some overhead but it works really well when you use
this for enough amount of data. normal way is good for just two
conditions.
There is no special syntax for that. You could make a function for that. Assuming at least Java 1.5:
public <T> boolean eitherOneEquals(T o1, T o2, T expectedValue) {
return o1.equals(expectedValue) || o2.equals(expectedValue);
}
if(eitherOneEquals(o1, o2, expectedValue)) {
// do something...
}

Is a return of 'false' a valid postcondition of a method?

I've been learning about postconditions, preconditions, and design by contract recently and I haven't been able to find an exact answer to this question.
To me, a postcondition seems to essentially be 'what the method is meant to have achieved' after being invoked.
Here's an example
//If x is not equal to y, do something with x and return true. Otherwise, return false.
public boolean example(int x)
{
if(x != y)
{
return true;
//do something with x.
}
else
{
return false;
}
}
When stating the postconditions of this method, would it make sense to say that it returning 'false' is one of them? Or is the postcondition only what is done with x?
Edit:
Here's a better example with an actual precondition -
public boolean example2(Example x)
{
if (x == a)
{
throw new IllegalArgumentException("x must not be the same as a");
}
if(x != y)
{
return true;
//do something with x.
}
else
{
return false;
}
}
You did not provide any preconditions nor postconditions in your example method. What you provided was a class invariant.
The precondition is checked in the method before the postcondition is checked. Often times this is done via assert for post-conditions.
A postcondition states what a method ensures if it has been called by
fulfilling its precondition. If the postcondition is violated although
the precondition holds, the method (the supplier) has broken the
contract (implementation error). In other words a postcondition is a
right to the customer and an obligation to the supplier.
Quote source: https://c4j-team.github.io/C4J/examples_postcondition.html
You are not returning true or false typically. The postcondition is handled by assertions. The Oracle page on this gives good examples:
/**
* Returns a BigInteger whose value is (this-1 mod m).
*
* #param m the modulus.
* #return this-1 mod m.
* #throws ArithmeticException m <= 0, or this BigInteger
* has no multiplicative inverse mod m (that is, this BigInteger
* is not relatively prime to m).
*/
public BigInteger modInverse(BigInteger m) {
if (m.signum <= 0)
throw new ArithmeticException("Modulus not positive: " + m);
if (!this.gcd(m).equals(ONE))
throw new ArithmeticException(this + " not invertible mod " + m);
... // Do the computation
assert this.multiply(result).mod(m).equals(ONE);
return result;
}
Basically, pre+postconditions can be anything, that verifies, that the given interface follows the required behaviour.
As an example:
List<E> is an interface. ArrayList<E> is a class, implementing List<E> and exposing expected behaviour. Imagine, you write a set of JUnit tests against List<E> and then execute them against ArrayList<E>. If your ArrayList<E> passes the test - it satisfies the contract of list behaviour.
`
//Precondition
List<Object> objectList = new ArrayList<Object>();
//Postcondition: a newly created list must be empty, if you did not put anything there
assertEquals(0,objectList.size);
//Precondition
Object someObject = new Object();
//Precondition
objectList.add(someObject);
//Postcondition: you get exactly the same element, that you have just put
assertEquals(1,objectList.size);
assertEquals(someObject,objectList.get(0));
`
In your case you have the following:
Precondition: x=something, but not equal to y
Postcondition: example(x) is true

To null check or not to do a null check?

Here is a code authored by Josh bloch, ( Linkedlist.java)
* #throws NullPointerException if the specified collection is null
*/
public boolean addAll(int index, Collection<? extends E> c) {
checkPositionIndex(index);
Object[] a = c.toArray();
int numNew = a.length;
if (numNew == 0)
return false;
Node<E> pred, succ;
if (index == size) {
succ = null;
pred = last;
} else {
succ = node(index);
pred = succ.prev;
}
Here I dont see any null ptr check for Collection c.
On contrary effective java very much stresses on parameter validation, emphasizing null pointer check. If an invalid parameter value is passed to a method and the method checks its parameters before execution, it will fail quickly and cleanly with an appropriate exception.
I need to know what I am missing ? In other words why did he not do a null check for addAll function ?
Because Object[] a = c.toArray(); will throw the stated exception anyway, if c is null.
Object[] a = c.toArray(); will obviously throw the NPE. What I would do in this case, would either check at the beginning if the param is null, and then return false (so it doesn't break the runtime flow - Objective-C style), OR assertIsNotNull at the beginning of the method, and specify it in the javadoc (e.g. "the thing must not be null, yo").
But that's just me. That's why APIs must always be well documented.

Categories

Resources