Java 8 Stream API 过滤 Map<Long, String> 示例
使用 Java 8 的 Stream API 可以轻松地根据条件过滤 Map<Long, String>。以下示例演示了如何仅保留字符串长度大于 3 的条目。
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
Map<Long, String> map = new HashMap<>();
map.put(1L, 'One');
map.put(2L, 'Two');
map.put(3L, 'Three');
map.put(4L, 'Four');
map.put(5L, 'Five');
// 过滤条件:字符串长度大于 3
Map<Long, String> filteredMap = map.entrySet().stream()
.filter(entry -> entry.getValue().length() > 3)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
// 输出过滤后的 Map
filteredMap.forEach((key, value) -> System.out.println(key + ': ' + value));
}
}
在这个例子中,我们首先创建一个 Map<Long, String> 对象,然后使用 Stream API 过滤它,仅保留字符串长度大于 3 的条目。最后,我们使用 forEach 方法打印过滤后的 Map 的键值对。
步骤:
- 使用
map.entrySet().stream()获取 Map 的所有条目并创建 Stream。 - 使用
filter(entry -> entry.getValue().length() > 3)过滤 Stream,仅保留字符串长度大于 3 的条目。 - 使用
collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))将过滤后的 Stream 收集到一个新的 Map 中。 - 使用
filteredMap.forEach((key, value) -> System.out.println(key + ': ' + value))打印过滤后的 Map。
通过这种方法,我们可以轻松地根据条件过滤 Map<Long, String> 对象,并提取我们需要的条目。
原文地址: https://www.cveoy.top/t/topic/qqRj 著作权归作者所有。请勿转载和采集!