java-在复杂的对象集合上循环

pn9klfpd  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(458)

我有一个关于在包含复杂对象的集合上循环的一般性问题。
我有一个 Collection<Object> ,其中包含 Array<E>LinkedHashMap<K,V> 我试图从中提取价值。
我试过各种各样的循环来获得键,值对,但是没有运气,比如;
物体看起来像;

  1. Collection<Object> dsidsToExclude = Arrays.asList(param.get("idsToExclude"));
  2. for(Object id : dsidsToExclude) {
  3. if(id instanceof ArrayList) {
  4. // Loop over the list of <K,V>
  5. for(Object kv : id) {
  6. // I want to get extract the kv pairs here..
  7. }
  8. }
  9. }

我想知道什么是最有效的方法,有什么建议吗?谢谢。

b4qexyjb

b4qexyjb1#

Arrays.asList(something) 将生成包含一个元素的列表。你不需要这么做。

  1. Object object = param.get("idsToExclude");

您可以检查对象并强制转换为列表。

  1. if (object instanceof List) {
  2. List list = (List) object;
  3. }

列表中的每一项都需要检查和转换。

  1. for (Object item : list) {
  2. if (item instanceof Map) {
  3. Map map = (Map) item;
  4. }
  5. }

您可以从Map项中获取键和值。

  1. Object key = map.getKey();
  2. Object value = map.getValue();

完整示例:

  1. Object object = param.get("idsToExclude");
  2. if (object instanceof List) {
  3. List list = (List) object;
  4. for (Object item : list) {
  5. if (item instanceof Map) {
  6. Map map = (Map) item;
  7. Object key = map.getKey();
  8. Object value = map.getValue();
  9. // You can cast key and value to other object if you need it
  10. }
  11. }
  12. }
展开查看全部
e3bfsja2

e3bfsja22#

只要输入集合的内容可以指定为 Collection<List<Map<K, V>>> (注意接口的使用) List 以及 Map 而不是实现 ArrayList 以及 LinkedHashMap ),则更适合实现类型为的泛型方法 K, V 摆脱 instanceof 和显式铸造:

  1. public static <K, V> doSomething(Collection<List<Map<K, V>>> input) {
  2. for (List<Map<K, V>> list : input) {
  3. for (Map<K, V> map : list) {
  4. for (Map.Entry<K, V> entry : map.entrySet()) {
  5. // do what is needed with entry.getKey() , entry.getValue()
  6. }
  7. }
  8. }
  9. }

同样,方法 forEach 可用于集合、列表和Map:

  1. public static <K, V> doSomethingForEach(Collection<List<Map<K, V>>> input) {
  2. input.forEach(list ->
  3. list.forEach(map ->
  4. map.forEach((k, v) -> // do what is needed with key k and value v
  5. System.out.printf("key: %s -> value: %s%n", k, v);
  6. );
  7. )
  8. );
  9. }

此外,还可以使用流api,特别是 flatMap 访问所有最里面Map的内容。或者, null 值可以按如下所示进行过滤

  1. public static <K, V> doSomethingStream(Collection<List<Map<K, V>>> input) {
  2. input.stream() // Stream<List<Map<K, V>>>
  3. .filter(Objects::nonNull) // discard null entries in collection
  4. .flatMap(List::stream) // Stream<Map<K, V>>
  5. .filter(Objects::nonNull) // discard null entries in list
  6. .flatMap(map -> map.entrySet().stream()) // Stream<Map.Entry<K, V>>
  7. .forEach(e -> System.out.printf(
  8. "key: %s -> value: %s%n", e.getKey(), e.getValue()
  9. ));
  10. }
展开查看全部

相关问题