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))); }
Advertisement
Answer
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());