Home > Blockchain >  How to improve the Java Stream method?
How to improve the Java Stream method?

Time:07-13

I would like to improve the following Java Stream method and to understand better how does anyMatch in Stream work.

In my example the get(blogContext.getBlogContextEnum().getTagName(), new String[0]) can have one or many tags. Will the anymatch iterate through each value that comes from the previous get?

When showAllTopics && currentFilterTag.equals("xxx:content/something") evaluates to true it should check that blogTags contain the resource tag. When showAllTopics && currentFilterTag.equals("xxx:content/something") evaluates to false it should check resource tag matches the currentFilterTag.

I could of course solve it with if statements but would like to learn using Streams for that.

The blogTags is a class variable of type private List<String> blogTags;

private boolean containsSelectedTag(Resource resource) {
        Stream<String> tagStream = Arrays.stream(resource.getValueMap().get(blogContext.getBlogContextEnum().getTagName(), new String[0]));
        boolean containsSelectedTag = showAllTopics && currentFilterTag.equals("xxx:content/something") ?
                tagStream.anyMatch(tag -> blogTags.contains(tag)) : tagStream.anyMatch(tag -> tag.contains(currentFilterTag));
        return containsSelectedTag;
    }

CodePudding user response:

Will this be considered as improvement?

private boolean containsSelectedTag(Resource resource) {
    Stream<String> tagStream = Arrays.stream(resource.getValueMap().get(blogContext.getBlogContextEnum().getTagName(), new String[0]));
    boolean containsSelectedTag = 
        tagStream.anyMatch(tag -> showAllTopics && currentFilterTag.equals("xxx:content/something") ? blogTags.contains(tag)) : tag.contains(currentFilterTag));
    return containsSelectedTag;
}
  • Related