java - Java - 循环复杂的对象集合
问题描述
我有一个关于循环包含复杂对象的集合的一般问题。
- 我有一个,
Collection<Object>
其中包含我试图从中提取值的一个。Array<E>
LinkedHashMap<K,V>
- 我尝试了各种循环来获取键、值对,但没有运气,比如;
对象看起来像;
Collection<Object> dsidsToExclude = Arrays.asList(param.get("idsToExclude"));
for(Object id : dsidsToExclude) {
if(id instanceof ArrayList) {
// Loop over the list of <K,V>
for(Object kv : id) {
// I want to get extract the kv pairs here..
}
}
}
我想知道有效地做到这一点的最佳方法是什么,有什么建议吗?谢谢。
解决方案
只要输入集合的内容可以指定为Collection<List<Map<K, V>>>
(注意使用接口List
和Map
而不是实现ArrayList
和),实现类型为的泛型方法以摆脱和显式转换LinkedHashMap
会更合适:K, V
instanceof
public static <K, V> doSomething(Collection<List<Map<K, V>>> input) {
for (List<Map<K, V>> list : input) {
for (Map<K, V> map : list) {
for (Map.Entry<K, V> entry : map.entrySet()) {
// do what is needed with entry.getKey() , entry.getValue()
}
}
}
}
类似地,方法forEach
可以用于集合、列表和映射:
public static <K, V> doSomethingForEach(Collection<List<Map<K, V>>> input) {
input.forEach(list ->
list.forEach(map ->
map.forEach((k, v) -> // do what is needed with key k and value v
System.out.printf("key: %s -> value: %s%n", k, v);
);
)
);
}
此外,还可以使用 Stream API,尤其flatMap
是访问所有最内层地图的内容。可选地,null
可以过滤值,如下所示
public static <K, V> doSomethingStream(Collection<List<Map<K, V>>> input) {
input.stream() // Stream<List<Map<K, V>>>
.filter(Objects::nonNull) // discard null entries in collection
.flatMap(List::stream) // Stream<Map<K, V>>
.filter(Objects::nonNull) // discard null entries in list
.flatMap(map -> map.entrySet().stream()) // Stream<Map.Entry<K, V>>
.forEach(e -> System.out.printf(
"key: %s -> value: %s%n", e.getKey(), e.getValue()
));
}
推荐阅读
- reactjs - next.js 应用程序需要 15-25 秒才能从谷歌应用程序引擎上的“冷”加载
- vb.net - 如何获得十个数字并显示最大和最小的数字?
- python - 如何根据顺序检测列表中的下一个任务
- mxgraph - 如何在 draw.io 中自动显示 mxGraphModel?
- asynchronous - 如何从 Tokio 的非主线程运行异步任务?
- javascript - Jest TypeError: Document.save 不是函数
- c - 在 C 中的数组中输入、查找和删除字符串
- c++ - 如何从找到的字符串中获取子字符串到 C++ 中的字符?
- reactjs - React JS 和 Redux:useSelector() 与 useStore()
- android - 蓝牙经典扫描不显示设备