[英]Java - Looping over complex collection of Objects
我有一个关于循环包含复杂 object 的集合的一般问题。
Collection<Object>
,其中包含我试图从中提取值的LinkedHashMap<K,V>
的Array<E>
。object 看起来像;
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
方法可用于集合、列表和 map:
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()
));
}
Arrays.asList(something)
将生成包含一个元素的列表。 你不需要这样做。
Object object = param.get("idsToExclude");
您可以检查 object 并投射到列表中。
if (object instanceof List) {
List list = (List) object;
}
列表中的每个项目都需要检查和转换。
for (Object item : list) {
if (item instanceof Map) {
Map map = (Map) item;
}
}
您可以从 map 项目中获取键和值。
Object key = map.getKey();
Object value = map.getValue();
完整示例:
Object object = param.get("idsToExclude");
if (object instanceof List) {
List list = (List) object;
for (Object item : list) {
if (item instanceof Map) {
Map map = (Map) item;
Object key = map.getKey();
Object value = map.getValue();
// You can cast key and value to other object if you need it
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.