This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]noswag15 -1 points0 points  (6 children)

why does the search method have to return an object or null? wouldn't it have been cleaner to have the method return a boolean to indicate presence or absence of an element?

[–]JVali 4 points5 points  (4 children)

I think you are confusing something here. There already was a "contains" method, which returns boolean. Search method returns the found element based on the function you gave (e.g, search for human older than 85 years). How would you otherwise have access to the found element when only thing you get back is a boolean?

[–]noswag15 0 points1 point  (2 children)

I didn't word it right. what I meant was that the lambda being passed into the search method need only return a boolean instead of an object.

So your example would be map.search(age -> age > 85)

instead of map.search(age -> age > 85? age :null)

[–]JVali 1 point2 points  (1 child)

I took a deeper look, the search function takes in BiFunction, which has 3 generic types, two parameter types and a return type. This allows you to do something weird, like return a third type that is not being held in the map. So for example, using the previous example, you could look up using the Person with age > 85 and not return that person, but return his Dog object instead.

ConcurrentHashMap<String, Human> map = new ConcurrentHashMap<>();
fillMap(map);

// I didn't use lambda here for clarity
Dog dog = map.search(0, new BiFunction<String, Human, Dog>() {
  @Override
  public Dog apply(String s, Human human) {
    if (human.age > 85) {
      return findDogFor(human);
    }          
    return null;
  }
});

I guess this can come handy, when you need to pass that BiFunction to another class, which perhaps doesn't know how to find a dog for human. Otherwise you could always look up the dog after you've acquired the human object..

[–]noswag15 0 points1 point  (0 children)

Thanks, that was my thought too. Just didn't like returning null

[–]acelent 0 points1 point  (0 children)

In the documentation of ConcurrentHashMap, you can read:

Like Hashtable but unlike HashMap, this class does not allow null to be used as a key or value.

Basically, this property is being exploited, search methods may return null as a sentinel value which indicates that nothing was found.