Sobes.tech
Junior — Middle

Can the stream() method be applied to a Map object in Java?

sobes.tech AI

Answer from AI

In Java, an object of type Map does not directly have a stream() method because Map is not a collection but an interface for key-value mapping. However, you can obtain streams from various views of the Map:

  • map.entrySet().stream() — stream of key-value pairs (Map.Entry<K, V>)
  • map.keySet().stream() — stream of keys
  • map.values().stream() — stream of values

Example:

Map<String, Integer> map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);

map.entrySet().stream()
   .filter(entry -> entry.getValue() > 1)
   .forEach(entry -> System.out.println(entry.getKey()));

Thus, the stream() method is applied to collections returned by Map methods, not directly to the Map itself.