Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

comparing List<Integer> to Integer Object using Java Stream

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading