I’m having issues with using streams in Java. Probably not the right way im doing. Can someone please point what’s going wrong.
I have a java class Users.java with List as follows:
/////..............
private List<Integer> userDocIdsToView = new ArrayList<Integer>();
@Transient
public List<Integer> getUserDocIdsToView() {
return userDocIdsToView;
}
public void setUserDocIdsToView(List<Integer> userDocIdsToView) {
this.userDocIdsToView = userDocIdsToView;
}
...////
Im trying to use this and compare this list with a Integer using stream as follows:
@RequestMapping(value = {"getDoc/{documentId}"}, method = RequestMethod.POST)
public ResponseEntity<?> getDoc(HttpServletRequest req, @PathVariable(required = true) String documentId) {
try {
System.out.println("Inside getDoc "+documentId+" ->"+"List "+userObj.getUserDocIdsToView()+" - "+Stream.of(userObj.getUserDocIdsToView()).anyMatch(num -> Objects.equals(num, Integer.valueOf(documentId))));
if(documentId != null && userObj.getUserDocIdsToView().size() > 0 && Stream.of(userObj.getUserDocIdsToView()).anyMatch(num -> Objects.equals(num, Integer.valueOf(documentId)))) {
System.out.println("Passed the condition");
}
}
}
The above code looks good but once I run , the sysout is as follows:
Inside getDoc 31 ->List [31, 48, 57, 59, 66, 67, 68, 73, 89, 102, 251] - false
I am converting String to Integer Object and comparing that with List. Where am i going wrong?
>Solution :
The problem is that you are using Stream.of(List). As a result you have a stream of one element and this element is the list. And of course, your list is not equal to the number.
userObj.getUserDocIdsToView().stream().anyMatch(num -> Objects.equals(num, Integer.valueOf(documentId))));
And don’t forget about potential NPEs, check that user object and docIdsToView are not null. Or use Optional