java在map< key>

qnakjoqk  于 2021-07-23  发布在  Java
关注(0)|答案(1)|浏览(307)

我正在用mongodb和spring进行练习,但我遇到了以下难题;在数据库中,我有以下信息:

[
  {
 "menu":"querys",
 "optionsList":[
 {
    "options":[
       "0001",
       "0022",
       "0014",
       "0041",
       "0042",
       "0043"
     ]
   }
 ]
},{..},{...}
]

java中对象的结构如下:

@Document(collection = "menu")
public class GetAllRules implements Serializable {

private static final long serialVersionUID = 7375796948388333325L;

@JsonProperty(value = "menu")
private String name;

@JsonProperty(value = "optionsList")
private List<Map<String, ?>> optionsList;

//Getters and Setters.

通过以下方法,我得到了json(我使用的是mongorepository),第一种方法得到了所有信息,第二种方法得到了内部Map,但我不知道如何迭代在选项中找到的信息,如果有人能帮我解决这个问题,我将不胜感激:

@GetMapping("/final")
public String obtener() {

List<GetAllRules> allRules = iGetMenuService.getAll(); // Mongo List

String key= "options";

for (GetAllRules rules : allRules) {
    for (Map<String, ?> internal : rules.getOptionsList()) {
        System.out.println(internal.get(key));
        }

    }

return "finalizado";
}

使用line system.out.println(internal.get(key));我得到了关键值​​我需要,但现在我不知道如何通过它一个接一个做一些具体的数据。

[0001, 0022, 0014, 0041, 0042, 0043]
[0238]
[1001, 1003]
[0108, 0109, 0102]
[0601, 0602, 0604, 0604]
[0603, 0901, 0901]
[0238]
[0001]

谢谢。

u4vypkhs

u4vypkhs1#

如何迭代在选项中找到的信息
选项字段只是另一个字符串数组/列表,因此可以在pojo中指定:

@JsonProperty(value = "optionsList")
private List<Map<String, List<String>>> optionsList;

这样,您就可以再添加一个迭代

for (GetAllRules rules : allRules) {
            for (Map<String, List<String>> internal : rules.getOptionsList()) {
                for (String value : internal.get(key)) {
                    System.out.println(value);
                    // will print "0001", ...
                }
            }
        }

更好的处理方法是使用java流—您不想使用太多嵌套循环,它可能如下所示:

allRules.stream()
                .map(GetAllRules::getOptionsList)
                .flatMap(Collection::stream)
                .flatMap(option -> option.get(key).stream())
                .forEach(System.out::println);

相关问题