我正在 Android 中完成一个类(class)作业,它会在屏幕上返回一个外卖列表,列出他们的地址、距我所在位置的距离以及卫生评级,我正在努力设置过滤器来过滤评级不符合标准,即 -1
因此,在这些情况下,我想将“exempt”返回到屏幕。这就是我到目前为止所拥有的
for (int i = 0; i < ja.length(); i++) {
JSONObject JO = (JSONObject) ja.get(i);
// if the rating of the restaurant is -1, exempt
// should be displayed
ratingValue.stream()
.filter(x->x.equals("-1"))
<< ifPresent.>> (System.out.println("Exempt"));
{
ConcatenateSearchResults();
}
ifPresent 似乎存在于 Java 中,但似乎不存在于 Android 中,并且我尝试的教程对我没有帮助。
protected JSONArray doInBackground(Void... voids) {
// if the searchUrl conversion is empty
if (!searchUrl.toString().isEmpty()) {
// do this instead
try {
URL url = new URL(searchUrl.toString());
URLConnection tc = url.openConnection();
InputStreamReader isr = new InputStreamReader(tc.getInputStream());
BufferedReader in = new BufferedReader(isr);
String line; // variable
// while line in (read in) is not equal to null
// create a new object and output as line in JSON
while ((line = in.readLine()) != null) {
ja = new JSONArray(line);
// run through the length of the array
for (int i = 0; i < ja.length(); i++) {
JSONObject JO = (JSONObject) ja.get(i);
// if the rating of the restaurant is -1, exempt
// should be displayed
ratingValue.stream()
.filter(x -> x.equals("-1"))
.findFirst()
.ifPresent(v -> System.out.println("Exempt"));
ConcatenateSearchResults();
// output to meet Basic Functionality requirement
businessNames.add(JO.getString("BusinessName"));
postCodes.add(JO.getString("PostCode"));
addressList1.add(JO.getString("AddressLine1"));
addressList2.add(JO.getString("AddressLine2"));
addressList3.add(JO.getString("AddressLine3"));
ratingValue.add(JO.getString("RatingValue"));
calcDistance.add(JO.getString("DistanceKM"));
}
}
isr.close();
in.close();
//return ja;
} catch (Exception e) {
this.exception = e;
return ja;
} finally {
//is.close();
}
}
return ja;
}
干杯
最佳答案
ifPresent()
与 Android 平台无关,它是 Java 的一部分。
在您的情况下,.filter()
该方法返回另一个过滤值流,不是单个值,而是一个流。
因此您不能在流上使用ifPresent()
,您需要获取单个值。为了使您的代码正确,您只需在 ifPresent()
之前添加 .findFirst()
即可,这将返回 ratingValue
中的第一个过滤值:
ratingValue.stream()
.filter(x -> x.equals("-1"))
.findFirst()
.ifPresent(v -> System.out.println("Exempt")
关于java - 在Java中使用过滤器时如何替换表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61123900/