Как отфильтровать поле через stream
Из сети получаю json файл и должен прочитать список весь и вернуть только те факты, у которых поле голосов не равно null (фильтр надо сделать через stream).
С сетью я разобрался, а вот как прочесть список и сделать фильтр поля через stream не понимаю.
Может кто подскажет. Заранее спасибо
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHeaders;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Stream;
public class Main {
public static final String REMOTE_SERVICE_URI = "https://raw.githubusercontent.com/netology-code/jd-homeworks/master/http/task1/cats";
public static final ObjectMapper mapper = new ObjectMapper();
public static void main(String[] args) throws IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create()
.setUserAgent("Service")
.setDefaultRequestConfig(RequestConfig.custom()
.setConnectTimeout(5000)
.setSocketTimeout(3000)
.setRedirectsEnabled(false)
.build())
.build();
HttpGet request = new HttpGet(REMOTE_SERVICE_URI);
request.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType());
CloseableHttpResponse response = httpClient.execute(request);
Arrays.stream(response.getAllHeaders()).forEach(System.out::println);
String body = new String(response.getEntity().getContent().readAllBytes(), StandardCharsets.UTF_8);
System.out.println(body);
List<ReformJson> reformJsons = mapper.readValue(response.getEntity().getContent(),
new TypeReference<>() {
}
);
reformJsons.forEach(System.out::println);
}
}
import com.fasterxml.jackson.annotation.JsonProperty;
public class ReformJson {
private final int userId;
private final int id;
private final String title;
private final String body;
public ReformJson(
@JsonProperty("userId") int userId,
@JsonProperty("id") int id,
@JsonProperty("title") String title,
@JsonProperty("body") String body
) {
this.userId = userId;
this.id = id;
this.title = title;
this.body = body;
}
public int getUserId() {
return userId;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public String getBody() {
return body;
}
@Override
public String toString() {
return "Post" + "" +
"\n userId=" + userId +
"\n id=" + id +
"\n title=" + title +
"\n body=" + body;
}
}
Ответы (1 шт):
Автор решения: Alex Rudenko
→ Ссылка
Не совсем понятно, какое из полей объекта ReformJson относится к голосам, поэтому в следующем примере список List<ReformJson> отфильтруем по полям body - чтобы они были не null и не пустые:
List<ReformJson> reformJsons = mapper.readValue(
response.getEntity().getContent(), new TypeReference<>() {}
)
.stream()
.filter(rj -> Objects.nonNull(rj.getBody()) && !rj.getBody().isEmpty())
.collect(Collectors.toList());