HashMap 用stream 过滤出value符合条件的数据
- User
HashMap 用stream 过滤出value符合条件的数据
- Assistant
可以使用 Java 8 的 Stream API 来过滤 HashMap 的 value 符合条件的数据。
假设有一个 HashMap<Integer, String>,现在要过滤出所有值中包含字符串 "hello" 的元素,可以使用下面的代码:
HashMap<Integer, String> map = new HashMap<>(); map.put(1, "hello world"); map.put(2, "hello java"); map.put(3, "hi there"); List<String> resultList = map.values().stream() .filter(value -> value.contains("hello")) .collect(Collectors.toList()); System.out.println(resultList);上面的代码使用了 HashMap 的 values() 方法获取所有的 value 值,然后使用 Stream API 中的 filter() 方法过滤出包含字符串 "hello" 的元素,最后使用 collect() 方法将过滤后的结果收集到一个列表中。最后输出结果为:
[hello world, hello java] - User
HashMap 用stream 过滤出value符合条件的key集合
- Assistant
可以使用 Java 8 的 Stream API 来过滤 HashMap 的 value 符合条件的数据,并获取对应的 key 值集合。
假设有一个 HashMap<Integer, String>,现在要过滤出所有值中包含字符串 "hello" 的元素,并获取对应的 key 值集合,可以使用下面的代码:
HashMap<Integer, String> map = new HashMap<>(); map.put(1, "hello world"); map.put(2, "hello java"); map.put(3, "hi there"); map.put(4, "good morning"); List<Integer> resultList = map.entrySet().stream() .filter(entry -> entry.getValue().contains("hello")) .map(Map.Entry::getKey) .collect(Collectors.toList()); System.out.println(resultList);上面的代码使用了 HashMap 的 entrySet() 方法获取所有的键值对,然后使用 Stream API 中的 filter() 方法过滤出包含字符串 "hello" 的元素,并使用 map() 方法将元素映射为其对应的 key 值,最后使用 collect() 方法将过滤后的 key 值收集到一个列表中。最后输出结果为:
[1, 2]
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.