Skip to content

Instantly share code, notes, and snippets.

@no13bus
Last active December 20, 2022 12:14
Show Gist options
  • Save no13bus/ddff9ad032909ce08db193933e5262fd to your computer and use it in GitHub Desktop.
Save no13bus/ddff9ad032909ce08db193933e5262fd to your computer and use it in GitHub Desktop.
check a json list is sorted or not
package com.usersapi;
import java.util.Date;
@lombok.Data
public class Item {
private Date timestamp;
}
package com.usersapi;
import com.alibaba.fastjson.JSONArray;
import java.io.InputStream;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Streamtest {
public static void main(String[] args) {
String jsonString = "[{\"timestamp\": \"2021-11-02T00:00:00Z\"}, {\"timestamp\": \"2021-11-02T00:00:00Z\"}, {\"timestamp\": \"2022-01-03T00:00:00Z\"}]";
List<Item> dateList = JSONArray.parseArray(jsonString, Item.class);
Boolean isNotSorted = IntStream.range(1, dateList.size())
.mapToObj(i -> dateList.get(i).getTimestamp().before(dateList.get(i-1).getTimestamp()))
.anyMatch(o->o);
if(isNotSorted){
throw new IllegalStateException("the json list is not sorted by time field");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment