Java Optional "while not null" equivalent [duplicate] - java

This question already has answers here:
do-while with Java8-Optional
(5 answers)
Closed 5 years ago.
Let us assume we start out with this code
while ((element = getNextElement()) != null) {
// do something
}
and want to rewrite it so that getNextElement() returns an Optional as opposed to something that might be null.
What would be the preferred way to do that? Something like
while ((element = getNextElement()) && element.isPresent()) {
}
... or is there a better way?
There is also
for (Optional<ElementType> element = getNextElement(); element.isPresent(); element = getNextElement()) {
// do something
}
Are there other/better options (pun intended, I suppose) for this?

Stream.generate(this::getNextElement) ...
The above would generate a Stream<Optional<Element>>. I believe that in java 9 there is a flatMap possibility.
For now:
Stream.generate(this::getNextElement)
.filter(Optional::isPresent)
.map(Optional::get)
.forEach(...);

Related

Iterating through json elements using java Streams [duplicate]

This question already has answers here:
How to create a Java 8 Stream from an iterator?
(4 answers)
Closed 1 year ago.
I'm trying to iterate through the elements in a JsonNode and check if they match some condition. I want to use Streams instead of using the classic iterator. I have code similar to this:
return Stream.generate(jsonNode.fields()::next)
.allMatch(entry -> {
switch (entry.getKey()) {
case "a":
return evaluateA(entry.getValue());
case "b":
return evaluateB(entry.getValue());
default:
return false;
}
});
But when I run this, I get a java.util.NoSuchElementException. I'm guessing the return statements within the switch case are causing this error. If that is the case, how do I handle this?
You can use gson-utils:
Reader in = null;
Iterator<Book> it = GsonUtils.readListLazy(in, Book.class);

How can I rewrite null checks with optional in a better way [duplicate]

This question already has an answer here:
Java 8 avoiding null pointer checks using Optional
(1 answer)
Closed 1 year ago.
I am having a small snippet of code. I would like to write it in a better way with fewer nested checks. How can I achieve it?
Item item = itemResponse.getItem();
Optional<Item> optionalItem = Optional.ofNullable(item);
if (optionalItem.isPresent()) {
List<NameValue> listValues = item.getValues();
Optional<List<NameValue>> optionalListValues = Optional.ofNullable(listValues);
if (optionalListValues.isPresent()) {
System.out.println(listValues);
}
}
Is there any concise way I can rewrite the above piece of code using Java 8?
You can make itemResponse.getItem() class to return Optional<Item> and use the chained map method which will executed only if Optional has value, and if map method return non null value then only final ifPresent(Consumer consumer) is executed
Optional<Item> item = itemResponse.getItem()
item.map(item::getValues)
.ifPresent(System.out::println);

How to check against null object with lambda expression before starting a stream [duplicate]

This question already has answers here:
Null safe Collection as Stream in Java 8
(6 answers)
Closed 3 years ago.
I have following method:
private Optional<Car> findCarByID(String id, CarResponse carResponse) {
return carResponse.getCars().stream()
.filter(car -> car.getID().equalsIgnoreCase(id))
.findFirst();
But carResponse can sometimes be null and I want to check this before trying to get the cars and stream them (null pointer exception is raised). I made the check with “if else” like this:
private Optional<Car> findCarByID(String id, CarResponse carResponse) {
if (carResponse!= null) {
return carResponse.getCars().stream()
.filter(car -> car.getID().equalsIgnoreCase(id))
.findFirst();
}
return Optional.empty();
}
Is there any way to include the check carResponse!= null in the beginning of lambda expression and not using “if else”?
It's correct, adding another optionals into the code can make it less readable. Although ternary operator can save you a couple of keystrokes.
return carResponse == null ? Optional.empty() : carResponse.getCars().stream()
.filter(car -> car.getID().equalsIgnoreCase(id))
.findFirst();

Java Stream - NullPointExeption when filter list [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I'm trying to filter from the list objects that field isActive have either set to N or null. Unfortunately, I get NullPointerException in method filter and I don't know what is wrong?
Code:
...
return dictionary.getAllPermissions().stream()
.filter(Objects::nonNull)
.filter(z->"N".equals(z.getIsActive().toString()) || z.getIsActive().equals(null)) //field isActive is Character
.collect(Collectors.toList());
You've got the ordering wrong, it should be:
.filter(z -> z.getIsActive() == null || "N".equals(z.getIsActive().toString()))
You should invert the checks here:
.filter(z->"N".equals(z.getIsActive().toString()) || z.getIsActive().equals(null))
to
.filter(z-> z.getIsActive() == null || "N".equals(z.getIsActive().toString()))
The idea is to first make sure that the value z.getIsActive() is not null before you can actually invoke the tostring() method to it.
z.getIsActive().toString() throws a NullPointExeption when isActive is null.
You said "field 'isActive' have either set to N or null", so if it's null all your z.getIsActive are null, so you need to check z.getIsActive==null

Searching through a collection of an array list pair [duplicate]

This question already has answers here:
How to compare two java objects [duplicate]
(5 answers)
Closed 9 years ago.
I am trying to search through a collection of an ArrayList if pairs. What I want to be able to do, is to go through the collection and find the first value in a pair and return the second value of that pair. The problem I am having is that the check I have to find the first value doesn't seem to be working, so every time I search, I end up returning null. I know that the problem exists with my if statement, but I cannot seem to sort out what it is I am doing wrong. Since this is a homework assignment, I can't show all the code to my pair class, or my pair list class, but I can show you the method I have for searching the first value:
public S findFirst(F firstValue) {
Iterator<Pair> myIter = this.iterator();
S tmp2 = null;
while (myIter.hasNext()) {
Pair tmp1 = myIter.next();
if (tmp1.getFirst() == firstCall) {
tmp2 = (S) tmp1.getSecond();
}
}
return tmp2;
}
If I throw in an else statement that just calls what I am attempting to do in my if check, like this:
else{
tmp2 = (S) tmp1.getSecond();
}
then whenever I test for the first value, I get the second value, so I know I am at least on the correct path, but I am assuming that I am doing something wrong with what I am checking for in my if statement. Does anyone know how I can correctly do this, (and please bear in mind that this is homework, so a guide to how to figure this out is far more valuable to me than just some random answer, I want to learn, not just be given an answer) Thanks in advance!
Don't use == to compare objects. Override and use equals().
I think
if (tmp1.getFirst() == firstCall)
should probably say
if (tmp1.getFirst().equals(firstValue))
The important difference is that == checks whether two expressions refer to the exact same object. You're more interested in knowing whether your two expressions actually refer to objects that are equal.
Try this:
if (tmp1.getFirst().equals(firstValue))
instead of
if (tmp1.getFirst() == firstCall)
Also you can override your own equals method.
You should never use == to compare objects.
Check How to compare two java objects
What Matt says, (don't use == ) but I think a bigger problem is that you don't return the 'first' encounter.... your if statement should look like:
public S findFirst(F firstValue) {
Iterator<Pair> myIter = this.iterator();
while (myIter.hasNext()) {
Pair tmp1 = myIter.next();
if (firstValue.equals(tmp1.getFirst())) {
return (S) tmp1.getSecond();
}
}
return null;
}

Categories