【问题标题】:Java 8 JSON optimisationJava 8 JSON 优化
【发布时间】:2022-10-12 21:59:56
【问题描述】:

我有一个带有学生列表的 JSON,如下所示 - 对于每个学生,我想打印爱好,如果没有爱好,则使用 Java 8 显示 NA。我编写了以下代码,该代码有效,但我必须使用 2地图。请建议是否可以优化此代码。

JSON

{
    "students":[
        {
            "fullName":"AAAAA",
            "standard":10,
            "hobbies":[
                "programming",
                "reading"
            ]
        },
        {
        }
    ]
}

爪哇 8

Map<String, List<Student>> studentMap = reportCard.getStudents().stream().collect(Collectors.groupingBy(Student::getFullName));
Map<String, String> studentMap2 = new TreeMap<>();
studentMap.keySet().forEach(key -> Optional.ofNullable(studentMap.get(key).get(0).getHobbies())
                        .ifPresentOrElse(hobbies -> studentMap2.put(key, hobbies.stream().map(String::trim).collect(Collectors.joining(";"))), () -> studentMap2.put(key, "NA")));

【问题讨论】:

  • 最好在Code Review 询问有关重新优化运行代码的问题

标签: java json java-stream collectors


【解决方案1】:

使用 Java 8

您可以使用collectors.toMap from爪哇 8获得所需的输出,如下面的代码所示:

这里,

  1. 我已经在文本块(来自 jdk15 的功能)使 json 具有可读格式。(您也可以使用简单的字符串格式)
  2. 我使用了collectors.toMap,其中我们将键作为学生姓名,对于我检查爱好列表是否不为空且不应为空的值,然后执行加入所有爱好的下游操作学生,否则它将有“NA”,我用过合并(a,b) -&gt; a + "," + b,如果存在同名学生的兴趣爱好,它将合并,TreeMap::new 将按自然顺序对爱好进行排序。

    代码:

    public class Test {
        public static void main(String[] args) throws JsonProcessingException {
            String input = """
                    {
                         "students": [
                             {
                                 "fullName": "AAAAA",
                                 "standard": 10,
                                 "hobbies": [
                                             "programming",
                                             "reading"
                                            ]
                             },
                             {
                                 "fullName": "BBBB",
                                 "standard": 12,
                                 "hobbies": [
                                             "music",
                                             "reading"
                                            ]
                             },
                             {
                                 "fullName": "CCCC",
                                 "standard": 12,
                                 "hobbies": [
                                            ]
                             },
                             {
                     
                             }
                         ]
                     }
                     
                    """;
            ObjectMapper mapper = new ObjectMapper();
            StudentData data = mapper.readValue(input,StudentData.class);
            
    
            Map<String,String> output =
                data.getStudentList().stream().filter(a -> a.getName()!=null)
                        .collect(Collectors.toMap(Student::getName,
                                x -> (x.getHobbies()!=null && !x.getHobbies().isEmpty() ? String.join(",",x.getHobbies()) : "NA")
        ,(a,b) -> a + "," + b,TreeMap::new));
            System.out.println(output);
        }
    }
    

    输出::

    {AAAAA=programming,reading, BBBB=music,reading, CCCC=NA}
    

【讨论】:

  • 出色的!正是我要找的.. 谢谢!
  • @astar 很高兴它解决了您的问题。
【解决方案2】:

我认为你应该拆分获取数据并打印它。

public static void main(String... args) {
    Root root = new Root();
    Map<String, Set<String>> studentHobbies = getStudentHobbies(root);
    printStudentHobbies(studentHobbies);
}

private static Map<String, Set<String>> getStudentHobbies(Root root) {
    return Optional.ofNullable(root.getStudents()).orElse(List.of()).stream()
                   .collect(Collectors.toMap(Student::getFullName,
                                             student -> Optional.ofNullable(student.getHobbies())
                                                                .orElse(Set.of())));
}

private static void printStudentHobbies(Map<String, Set<String>> studentHobbies) {
    studentHobbies.forEach((fullName, hobbies) ->
                                   System.out.format("%s - %s
",
                                                     fullName,
                                                     hobbies.isEmpty() ? "NA" : hobbies));
}

以防万一,我们有以下课程

private static class Root {

    private List<Student> students;

}

private static class Student {

    private String fullName;
    private int standard;
    private Set<String> hobbies;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-09
    • 2014-05-16
    • 2017-03-01
    • 2015-12-29
    • 2015-05-15
    • 2020-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多