Iterating through json elements using java Streams [duplicate] - java

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);

Related

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 mock the function in a loop using Mockito in Java to return different value for each iteration [duplicate]

This question already has answers here:
How to tell a Mockito mock object to return something different the next time it is called?
(5 answers)
Closed 2 years ago.
I am new to using Mockito. In my logic I need to mock a function that is inside the loop and for every iteration, it should return different value.
Example :
for(value : values )
{
int i = getValue(value);
i=i+1;
}
if(i=somevalue)
{
some code
}
else
{
Some other code
}
So if I mock getValue() method to return a particular value. Everytime, it is returning the same value and only one part of if else is covered.
Can you please suggest me a way such that everytime in the loop getValue() is returned different value.
Thank you !
Since you have an input in getValue() you can use that.
when(mockFoo.getValue(value1).thenReturn(1);
when(mockFoo.getValue(value2).thenReturn(2);
when(mockFoo.getValue(value2).thenReturn(3);
But if you just don't care you can return different values in a sequence.
when(mockFoo.getValue(any()))
.thenReturn(0)
.thenReturn(1)
.thenReturn(-1); //any subsequent call will return -1
// Or a bit shorter with varargs:
when(mockFoo.getValue())
.thenReturn(0, 1, -1); //any subsequent call will return -1
Also please note, that if(i=somevalue) will always be true, you might want to use if (i == somevalue).

Why null is not equal to null? [duplicate]

This question already has answers here:
How to compare null value from the JsonObject in java
(7 answers)
Closed 3 years ago.
I dont understand what is happening in my application. I'm sending PUT request with updates from Angular project to java api. I have a method that validates query parameters from the put request, the method looks like this:
private JsonObject validateRequestBody(JsonElement requestBody) {
if (!(requestBody instanceof JsonObject)) {
throw new IllegalArgumentException("Request body cannot be case to JSON object");
}
JsonObject bodyObj = requestBody.getAsJsonObject();
System.out.println(bodyObj.get("entityIri").equals(null));
if (bodyObj.get("entityIri") == null) {
System.out.println("null");
throw new IllegalArgumentException("Request body must contain entity IRI");
}
return bodyObj;
}
As you can see, I'm just trying to check if the enityIri paramter is equal to null. To test it, Im sending null as entityIri from Angular project. I tried to compare them with equal method and with ==, but in both cases the output is always false. Could someone explain me why they are not equal? Is it because I'm passing it to JsonObject?
I attach a screenshot from debugging (I cut out irrelevant parts).
Try to use isJsonNull method:
provides check for verifying if this element represents a null value
or not.
if (bodyObj.get("entityIri").isJsonNull()) {
...
}
Of course, you need to check whether bodyObj.get("entityIri") is not null before. I did not add it statement to make statement clear.

Java Optional "while not null" equivalent [duplicate]

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(...);

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