java8 stream对象探索(1)(JSONObject和JSONArray操作)

自从接触了stream流对象之后,我习惯于使用流对象进行List的处理,在最近的一段业务开发中,用到的JSON操作比较多,而com.alibaba.fastjson下的JSONObject,JSONArray本质上来说其实是map和list,仅以记录其一部分流操作;

 

1 取最后一条数据

stream对象存在方法findFirst,我们可以很方便的取到第一条数据,但它却没有findLast方法,需要取到最后一条数据,我们可以将数组逆序,然后再取最后一条数据:

JSONArray jsonArray = JSONArray.parseArray("[{\"name\":\"草根\",\"sex\":\"man\",\"date\":\"2018-01-01\"},{\"name\":\"merry\",\"sex\":\"woman\",\"date\":\"2017-01-01\"},{\"name\":\"liming\",\"sex\":\"woman\",\"date\":\"2016-01-01\"}]");
JSONObject jsonObject = (JSONObject)jsonArray.stream().sorted((a,b) -> -1).findFirst().get();
System.out.println(jsonObject);
/**
* out :
*      {"date":"2016-01-01","sex":"woman","name":"liming"}
**/

 

2 清空json对象中的某个数组(该数组位于JSON对象内部多层)

JSONObject jsonObject = JSONObject.parseObject("{\"1\": {\"name\":\"maple\",\"sex\":\"man\",\"childrens\":[{\"name\":\"草根\",\"sex\":\"man\",\"date\":\"2018-01-01\"},{\"name\":\"merry\",\"sex\":\"woman\",\"date\":\"2017-01-01\"},{\"name\":\"liming\",\"sex\":\"woman\",\"date\":\"2016-01-01\"}]}}");
jsonObject.forEach((key, val) -> {
    JSONObject obj = (JSONObject) val;
    JSONArray array = obj.getJSONArray("childrens");
    array.clear();
    obj.put("childrens",array);
});
System.out.println(jsonObject);
/**
* out :
*      {"1":{"childrens":[],"sex":"man","name":"maple"}}
**/

 

3 收集对象属性重新成一个数组

有时候我们需要对对象进行再次拼装以形成我们方便使用的数据状态:

JSONArray jsonArray = JSONArray.parseArray("[{\"1\": {\"name\":\"maple\",\"sex\":\"man\",\"childrens\":[{\"name\":\"草根\",\"sex\":\"man\",\"date\":\"2018-01-01\"},{\"name\":\"merry\",\"sex\":\"woman\",\"date\":\"2017-01-01\"},{\"name\":\"liming\",\"sex\":\"woman\",\"date\":\"2016-01-01\"}]}}]");
jsonArray = jsonArray.stream().map(obj -> {
JSONObject returnObj = new JSONObject();
    JSONObject jsonObj = (JSONObject)obj;
    jsonObj.forEach((key,val) -> {
        returnObj.put(key,((JSONObject)val).getJSONArray("childrens"));
    });
    return returnObj;
}).collect(Collectors.toCollection(JSONArray::new));
System.out.println(jsonArray);
/**
* out :
*      [{"1":[{"date":"2018-01-01","sex":"man","name":"草根"},{"date":"2017-01-01","sex":"woman","name":"merry"},{"date":"2016-01-01","sex":"woman","name":"liming"}]}]
**/

 

4 过滤数据并按时间字符串排序

JSONObject jsonObject = JSONObject.parseObject("{\"1\": {\"name\":\"maple\",\"sex\":\"man\",\"childrens\":[{\"name\":\"草根\",\"sex\":\"man\",\"date\":\"2018-01-01\"},{\"name\":\"merry\",\"sex\":\"woman\",\"date\":\"2017-01-01\"},{\"name\":\"liming\",\"sex\":\"woman\",\"date\":\"2016-01-01\"}]}}");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Comparator<Object> dateComparator = (a, b) -> {
    int result = 0;
    try {
         Date dt1 = df.parse(((JSONObject)a).getString("date"));
         Date dt2 = df.parse(((JSONObject)b).getString("date"));
         result = dt1.compareTo(dt2);
    } catch (Exception ex) {
         ex.printStackTrace();
    } finally {
          return result;
    }
};
jsonObject.forEach((key, val) -> {
    JSONObject obj = (JSONObject) val;
    if (obj.getJSONArray("childrens") != null) {
          JSONArray array = obj.getJSONArray("childrens");
          array = array.stream().filter(arrObj -> !"merry".equals(((JSONObject) arrObj).getString("name")))
                  .sorted(dateComparator)
                  .collect(Collectors.toCollection(JSONArray::new));
          obj.put("childrens", array);
    } else {
            obj.put("childrens", new JSONArray());
    }
});
System.out.println(jsonObject);
/**
* out :
*      {"1":{"childrens":[{"date":"2016-01-01","sex":"woman","name":"liming"},{"date":"2018-01-01","sex":"man","name":"草根"}],"sex":"man","name":"maple"}}
**/

 

原文地址:https://zhuanlan.zhihu.com/p/36865573 

https://blog.csdn.net/banqgg/article/details/86625695

 

  • 4
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Java 8中的Stream API来实现将Map转换为JSONObject。具体步骤如下: 1. 使用entrySet()方法将Map转换为Set<Map.Entry<K, V>>类型的集合。 2. 调用Stream API中的map()方法,将每个Map.Entry对象转换为JSONObject中的键值对。 3. 使用collect()方法将所有的JSONObject键值对收集到一个新的JSONObject对象中。 下面是一个示例代码: ``` import org.json.JSONObject; import java.util.Map; import java.util.stream.Collectors; public class MapToJson { public static JSONObject mapToJson(Map<String, Object> map) { JSONObject json = map.entrySet() .stream() .map(entry -> { Object value = entry.getValue(); if (value instanceof Map) { value = mapToJson((Map) value); } else if (value instanceof List) { value = listToJson((List) value); } return new JSONObject().put(entry.getKey(), value); }) .reduce(new JSONObject(), JSONObject::put, JSONObject::put); return json; } public static JSONArray listToJson(List<Object> list) { JSONArray json = list.stream() .map(value -> { if (value instanceof Map) { value = mapToJson((Map) value); } else if (value instanceof List) { value = listToJson((List) value); } return value; }) .collect(Collectors.toCollection(JSONArray::new)); return json; } } ``` 这个代码可以将Map转换为JSONObjectJSONArray,具体使用方式可以根据需求进行调整。需要注意的是,在使用Stream API时,需要对Map中的值进行类型判断并递归处理,这样才能保证最终的JSONObjectJSONArray对象正确无误。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值