将多个列表合并到流中的一个对象列表?

ha5z0ras  于 2021-06-26  发布在  Java
关注(0)|答案(1)|浏览(399)

我有这样的代码。它使用jsoap库。我得到标题,磁铁,种子,leechers(这两个一起作为torrentstats)从torrent网站。现在我想把它们合并到一个列表中,当然在标准for循环中很容易做到,但是有没有办法在流中Map或平面Map它们呢?

Document html = Jsoup.connect(SEARCH_URL + phrase.replaceAll("\\s+", "%20")).get();

Elements elements1 = html.select(".detLink");
Elements elements2 = html.select("td > a[href~=magnet:]");
Elements elements3 = html.select("table[id~=searchResult] tr td[align~=right]");

List < String > titles = elements1.stream()
    .map(Element::text)
    .collect(Collectors.toList());

List < String > magnets = elements2.stream()
    .map(e - > e.attr("href"))
    .collect(Collectors.toList());

List < TorrentStats > torrentStats = IntStream.iterate(0, i - > i + 2)
    .limit(elements3.size() / 2)
    .mapToObj(i - > new TorrentStats(Integer.parseInt(elements3.get(i).text()),
        Integer.parseInt(elements3.get(i + 1).text())))
    .collect(Collectors.toList());

//is there any way to use map or flatmap to connect these 3 list into this one?
List < Torrent > torrents = new ArrayList < > ();
for (int i = 0; i < titles.size(); i++) {
    torrents.add(new Torrent(titles.get(i), magnets.get(i), torrentStats.get(i)));
}
0x6upsns

0x6upsns1#

你可以用 IntStream.range 迭代索引。

List<Torrent> torrents = IntStream.range(0, titles.size())
      .mapToObj(i -> new Torrent(titles.get(i), magnets.get(i), torrentStats.get(i)))
      .collect(Collectors.toList());

相关问题