Java Stream How to - Search and loop ConcurrentHashMap








Question

We would like to know how to search and loop ConcurrentHashMap.

Answer

import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
//from   w  w  w  . jav a 2  s  .  c  om
public class Main {

  public static void main(final String[] args) {
    ConcurrentHashMap<Integer, UUID> concurrentHashMap = new ConcurrentHashMap<>();

    for (int i = 0; i < 100; i++) {
      concurrentHashMap.put(i, UUID.randomUUID());
    }

    int threshold = 1;

    concurrentHashMap.forEachValue(threshold, System.out::println);

    concurrentHashMap.forEach((id, uuid) -> {
      if (id % 10 == 0) {
        System.out.println(String.format("%s: %s", id, uuid));
      }
    });

    String searchResult = concurrentHashMap.search(threshold, (id, uuid) -> {
      if (String.valueOf(uuid).contains(String.valueOf(id))) {
        return new String(id + ":" + uuid);
      }
      return null;
    });

    System.out.println(searchResult);
  }

}

The code above generates the following result.