1

I have code like this. It uses JSoap library. I am getting titles, magnets, seeds, leechers (these two together as TorrentStats) from torrent site. Now I want to merge them inside one List, of course it's pretty easy to do it in standard for loop but is there any way to map or flatmap them in stream?

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)));
}

1 Answer 1

3

You can use IntStream.range to iterate over the indexes.

List<Torrent> torrents = IntStream.range(0, titles.size())
      .mapToObj(i -> new Torrent(titles.get(i), magnets.get(i), torrentStats.get(i)))
      .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

2 Comments

Oh, I did the same above when merging to TorrentStats <facepalm>, thank you
Ye, I was waiting maybe for another solutions but I think there will not be better or cleaner solution for this :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.