[英]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.