Skip to content Skip to sidebar Skip to footer

Add Item To Arraylist At Specific Interval

I am trying to add an element to ArrayList after every 4 items. ArrayList after this should be like, item|item|item|item|new_item|item|item|item|item|new_item|item... So I use the

Solution 1:

To make it more readable, you can also try using a new ArrayList. Loop through an existing array list and add elements to new ArrayList with an condition of every 4th element is new.

    List<NewsData> myNews = new ArrayList<>();
    List<NewsData> newNews = new ArrayList<>();

    for (int i = 0; i < myNews.size(); i++) {
        if (i % 4 == 0) {
            NewsData news = new NewsData();
            news.setId(999);
            news.setItem_type(3);
            news.setCat_id(97);
            myNews.add(news);
        }
        newNews.add(myNews.get(i));
    }

Solution 2:

The problem is that your index gets messed up by inserting elements. The best way to solve this common problem is to traverse the list the other way around, i.e., start with the last item.

for (int i=myNews.size()-1;i>0;i--) {           
  if (i%4==0) {
    NewsData news = new NewsData();
    news.setId(999);
    news.setItem_type(3);
    news.setCat_id(97);
    myNews.add(i,news);
  }
}

If you want to avoid looping over all the items and to only iterate where you want to insert items, you have to figure out the last item where you want to insert:

intlast = myNews.size() / 4 * 4;
if (last == myNews.size())
    last -= 4;
for (int i = last; i > 0;i -= 4) {           
    NewsData news = new NewsData();
    news.setId(999);
    news.setItem_type(3);
    news.setCat_id(97);
    myNews.add(i, news);
}

Post a Comment for "Add Item To Arraylist At Specific Interval"