java.util.NoSuchElementException: No value present Java 8 Lambda [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I got this. But my list is not empty and they have element with code "ADPL". Why this return me NoSuchElement ?
String retour = CodeExecutionChaine.A.getCode();
if (!lstChaines.isEmpty()) {
retour = lstChaines.stream()
.filter(t -> t.getNomChaine() == Chaines.ADPL.getCode())
.map(Chaine::getStatutChaine)
.findFirst()
.orElse(CodeExecutionChaine.A.getCode());
The enum Chaines
public enum Chaines {
ADPL("ADPL"),
ADIL("ADIL"),
ADSL("ADSL");
private String code = "";
Chaines(String code) {
this.code = code;
}
public String getCode() {
return this.code;
}
}
This is the same for CodeExecutionChaine

Change t -> t.getNomChaine() == Chaines.ADPL.getCode() to t -> t.equals(Chaines.ADPL.getCode()).
== checks for identity. Therefore, == will result into true only if two references point to the same object. On the other hand, equals checks for equality. Two references that don't point to the same object but have similar properties are still considered equal. You get a NoSuchElementException because you used == to filter your Stream which resulted in zero elements satisfying the condition.

Related

Not able to remove null from a list in Java [duplicate]

This question already has answers here:
Why do I get a NullPointerException when comparing a String with null?
(4 answers)
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 days ago.
I have a list of a bean class newSRMAPIResponseBeanList wherein I am always getting a null object at last which I am trying to remove but it is resulting in null pointer exception if I handle the exception, it is not removing that null value. Below is my code.
for (int i = 0; i < newSRMAPIResponseBeanList.size(); i++) {
try {
if (newSRMAPIResponseBeanList.get(i).getCompanyId().equals(null)) {
newSRMAPIResponseBeanList.remove(i);
}
}catch(Exception e) {
e.printStackTrace();
}
}
In the if condition itself it is failing. I want to remove the null value of company ID. Actually newSRMAPIResponseBeanList is a list of List<NewSRMAPIResponseBean> newSRMAPIResponseBeanList = new ArrayList<>(); and the bean class is as follows.
public class NewSRMAPIResponseBean {
private String companyId;
private String investmentId;
private String performanceId;
private List<String> values;
}
Is there any way I can remove that null value? I also tried using Java streams as follows.
List<NewSRMAPIResponseBean> finalList=newSRMAPIResponseBeanList.parallelStream()
.filter(Objects::nonNull)
.collect(Collectors.toList());
This too did not work.
I want to remove the null value of company ID.
I presume you mean remove the list element if the Id is null. So It's not the bean that is null, it is the companyId. Assuming you have getters, try it like this. If the Id is not null, let it pass thru.
List<NewSRMAPIResponseBean> finalList=newSRMAPIResponseBeanList.parallelStream()
.filter(bean->bean.getCompanyId() != null)
.collect(Collectors.toList());
You can also do it in a simple loop.
To avoid a ConurrentModificationException, use an iterator.
Iterator<NewSRMAPIResponseBean> iter = newSRMAPIResponseBeanList.iterator();
while (iter.hasNext()) {
if (iter.next().getCompanyId() == null) {
iter.remove();
}
}

Check if String is null from a Class [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
i know that my question is a duplicate of some question here before, i tried every solution that i see from that, but no solution work for me
i have a class named FilingModel and a method name getReason, i always get a null value to my tvReason TextView
public class FilingAdapter extends RecyclerView.Adapter<FilingAdapter.FilingHolder> {
List<FilingModel> lists;
#Override
public void onBindViewHolder(#NonNull FilingHolder holder, int position) {
FilingModel model = lists.get(position);
holder.tvReason.setText(model.getReason());
}
}
public class FilingModel {
private String reason;
public FilingModel(String reason) {
this.reason = reason;
}
public String getReason() {
if ( reason.isEmpty() || TextUtils.isEmpty(reason) || reason.equals(null)) {
reason = "-";
}
return reason;
}
}
String checks for null are rather straight forward (once you have done it):
First you want to check if the instance is null (otherwise all further manipulation might fail):
if(reason == null)
Then you want to check if it is empty as you already did it but maybe you want to trim it first (to remove all whitespaces):
if(reason == null || reason.trim().isEmpty())
as you can see you can chain the conditions with or since Java will stop evaluating the conditions once one of them was found true . So if your string is null, Java will not evaluate if it is empty.
And that's all you need, null and isEmpty (and optionally with a trim())
public String getReason() {
if(reason==null || reason.trim().isEmpty()){
reason = "-";
}
return reason;
}
Give type to your variable reason. For example String.
private String reason;
+
if(reason == null)

If statement doesn't work, the program enters directly the "else" statement [duplicate]

This question already has answers here:
How != and == operators work on Integers in Java? [duplicate]
(5 answers)
Closed 5 years ago.
I am trying to write a program which detects "idle" status but I don't see the problem in my code. Could someone help me please with an useful tip? Here's my code:
package idlestatus;
import java.awt.MouseInfo;
public class Idlestatus {
public static void main(String[] args) throws InterruptedException {
Integer firstPointX = MouseInfo.getPointerInfo().getLocation().x;
Integer firstPointY = MouseInfo.getPointerInfo().getLocation().y;
Integer afterPointX;
Integer afterPointY;
while (true) {
Thread.sleep(10000);
afterPointX = MouseInfo.getPointerInfo().getLocation().x;
afterPointY = MouseInfo.getPointerInfo().getLocation().y;
if (firstPointX == afterPointX && firstPointY == afterPointY) {
System.out.println("Idle status");
} else {
System.out.println("(" + firstPointX + ", " + firstPointY + ")");
}
firstPointX = afterPointX;
firstPointY = afterPointY;
}
}
}
If is working but your condition is always getting false, because you are using Integer instead of primitive int. Note that when you use Object, compare them with .equals() method instead of ==.
Therefore :
if (firstPointX.equals(afterPointX) && firstPointY.equals(afterPointY)) {
//your code...
}
See this for difference between == and Object.equals() method.
And as mentioned in comments, you can always use int for such purposes, instead of Integer.
See this for difference between Integer and int.
You are comparing two objects memory addresses , which is Integer object(wrapper class).
if (firstPointX == afterPointX && firstPointY == afterPointY)
What you want to do is compare values in these two objects. To do that you need to use like below:
if (firstPointX.equals(afterPointX) && firstPointY.equals(afterPointY))
Wrapper / covering classes:
There is a wrapper class for each primitive data type.
Primitive types are use for performance reasons(Which better for your
program).
Cannot create objects using primitive types.
Allows a way to create objects and manipulate basic types(i.e.
converting types).
Exsample:
Integer - int
Double - double

If-condition never executes despite correct condition [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I have a simple piece of code to validate a username and a password.
public boolean isValid(String u, String p) {
if (u=="admin" && p=="password1") {
return true;
} else if (u=="user" && p=="password2") {
return true;
} else {
return false;
}
}
I've tried debugging it, and when it runs, u has the value "admin" and p has the value "password1", but it just skips the first condition. I must have done something wrong, but I can't figure out what.
== should not be used for String comparison. Use equals() instead.

Why doesn't my string comparison with == work? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I have this, in my onPostExecute :
String test = currentActivity.getClass().getSimpleName();
if(test == "SplashScreen"){
Log.e("OK",test);
} else {
Log.e("OK",test);
}
The problem is, the value of test is "SplashScreen" (that we can see with the log), but the code never goes in the if, only in the else.
Why does this happen?
As the others had already said you can not use the == operator on strings.
The reason for this is that strings are objects and not primitive datatypes.
With that said the == operator will check if the two strings has the same memory point in the memory if I'm not mistaken.
use equals to compare strings:
if(test.equals("SplashScreen"){
Log.e("OK",test);
} else {
Log.e("OK",test);
}
You can't use == on strings. You should use:
"SplashScreen".equals(test)
Test might be null, it is better to call equals() on "SplashScreen" since you know that it is no null.
Don't compare string with == use .equals()
String test = currentActivity.getClass().getSimpleName();
if(test.equals("SplashScreen")){
Log.e("OK",test);
} else {
Log.e("OK",test);
}
It's better to use equalsIgnoreCase(String string).
String test = currentActivity.getClass().getSimpleName();
if(test.equalsIgnoreCase("SplashScreen")){
Log.e("OK",test);
} else {
Log.e("OK",test);
}

Categories

Resources