简体   繁体   中英

How to extract two values from a json list and save them to a map?

I have a JSON file with a lot of fields. I need to extract two fields to the map: x and y. I am trying to extract the x field using list.stream().Map(x -> x.get ('x') ..... But I want to join this so that its value is the y field in the list.

List<JSONObject> jsonList = new ArrayList<>();
HashMap<Object, Object> tempMap = new HashMap<>();

Use Collectors.groupingBy with an additional downstream collector to summarize the value, which could be Collectors.mapping with appropriate Collectors.summingInt / Collectors.summingLong / Collectors.summingDouble for numeric values, Collectors.joining for strings, or Collectors.reducing , etc., but it would be needed to specify the type of the value because + operator (numeric addition or string concatenation) cannot be applied to simple Object :

HashMap<Object, String> tempMap = jsonList.stream()
    .collect(Collectors.groupingBy(
        x -> x.get("x"), // key
        Collectors.mapping(
            x -> Objects.toString(x.get("y")), 
            Collectors.joining("|") // String value(s) delimited with pipe '|'
        ) 
    ));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM