Search code examples
javalistcontains

How can i check and return if there is value in a list with values in JSON format in java


I want to see if in my List is live67 parameter, I have seen other posts on how to see if there is a value in the List, however my list has values in JSON format and it is not working for me. After that I want to return 3da2f0db339742f257ecbe737855cd6e -> value for test67.

I try:

streamService.getAllStreams().contains("test67")

My List:

[
    {
        "key": "3da2f0db339742f257ecbe737855cd6e",
        "streamName": "test67"
    },
    {
        "key": "35ad38ffb46c2ba97306ca931e003481",
        "streamName": "test68"
    }
]

in streamDao class:

public List<Stream> selectAllStreams();

in StreamService:

public List<Stream> getAllStreams(){
        return streamDao.selectAllStreams();
    }

in StreamController:

@GetMapping("/getList")
public List<Stream> getAllStreams(){
    if(streamService.getAllStreams().contains("test67")){
    return streamService.getAllStreams();
    }
    else{
        return null;
    }
}

always get null

This is my Stream class:

public class Stream {

    String key;
    String streamName;

    public Stream(String streamName, String key){

        this.streamName = streamName;
        this.key = key;
    }

    public String getKey() {
        return key;
    }

    public String getStreamName() {
        return streamName;
    }

}

Solution

  • Have a look at the java stream api

    public List<Stream> getAllStreams(){
        var optionalStream = streamService.getAllStreams().stream()
           .filter(str -> str.getStreamName().equals("test67")).findFirst();
    
        if (optionalStream.isPresent()) {
             return streamDao.selectAllStreams();
             // return optionalStream.get().getKey(); To return the Key value of stream test67
        }
        return null;
    }