3 回答

TA貢獻1836條經驗 獲得超4個贊
如果要使用 JAVA Stream API,對象必須是 Iterable。正如@Michal 提到的,您可以將其更改為 Collection。從@Michal 的回答中,我們可以簡化它,就像:
public class JsonArrayIntersectTest {
private boolean anyMatch(JSONArray first, JSONArray second) throws JSONException {
Set<Object> firstAsSet = convertJSONArrayToSet(first);
Set<Object> secondIdsAsSet = convertJSONArrayToSet(second);
// use stream API anyMatch
return firstAsSet.stream()
.anyMatch(secondIdsAsSet::contains);
}
private Set<Object> convertJSONArrayToSet(JSONArray input) throws JSONException {
Set<Object> retVal = new HashSet<>();
for (int i = 0; i < input.length(); i++) {
retVal.add(input.get(i));
}
return retVal;
}
@Test
public void testCompareArrays() throws JSONException {
JSONArray deviation = new JSONArray(ImmutableSet.of("1", "2", "3"));
JSONArray deviationIds = new JSONArray(ImmutableSet.of("3", "4", "5"));
Assert.assertTrue(anyMatch(deviation, deviationIds));
deviation = new JSONArray(ImmutableSet.of("1", "2", "3"));
deviationIds = new JSONArray(ImmutableSet.of("4", "5", "6"));
Assert.assertFalse(anyMatch(deviation, deviationIds));
}
}

TA貢獻1864條經驗 獲得超6個贊
任何匹配返回 true 的要求都可以重新表述為非空交集 return true。將JSONArrayinto轉換Collection為很容易做到這一點,例如像這樣
public class JsonArrayIntersectTest {
private boolean anyMatch(JSONArray first, JSONArray second) throws JSONException {
Set<Object> firstAsSet = convertJSONArrayToSet(first);
Set<Object> secondIdsAsSet = convertJSONArrayToSet(second);
//Set<Object> intersection = Sets.intersection(firstAsSet, secondIdsAsSet); // use this if you have Guava
Set<Object> intersection = firstAsSet.stream()
.distinct()
.filter(secondIdsAsSet::contains)
.collect(Collectors.toSet());
return !intersection.isEmpty();
}
Set<Object> convertJSONArrayToSet(JSONArray input) throws JSONException {
Set<Object> retVal = new HashSet<>();
for (int i = 0; i < input.length(); i++) {
retVal.add(input.get(i));
}
return retVal;
}
@Test
public void testCompareArrays() throws JSONException {
JSONArray deviation = new JSONArray(ImmutableSet.of("1", "2", "3"));
JSONArray deviationIds = new JSONArray(ImmutableSet.of("3", "4", "5"));
Assert.assertTrue(anyMatch(deviation, deviationIds));
deviation = new JSONArray(ImmutableSet.of("1", "2", "3"));
deviationIds = new JSONArray(ImmutableSet.of("4", "5", "6"));
Assert.assertFalse(anyMatch(deviation, deviationIds));
}
}
但是,與直接使用 API 的初始版本相比,代碼要多得多JSONArray。它還會產生比直接 API 版本更多的迭代JSONArray,這可能是也可能不是問題。然而,總的來說,我認為在傳輸類型上實現領域邏輯并不是一個好的做法,例如JSONArray并且總是會轉換成領域模型。
另請注意,生產就緒代碼還會null對參數進行檢查。

TA貢獻1828條經驗 獲得超4個贊
您可以使用 XStream 來處理 JSON 映射
或者根據您檢索字符串的邏輯,您可以比較為
?JSONCompareResult?result?=?JSONCompare.compareJSON(json1,?json2,?JSONCompareMode.STRICT); ?System.out.println(result.toString());
添加回答
舉報