Solved Looping through ArrayList<String> with an Iterator

Discussion in 'Spigot Plugin Development' started by DecisionsYT, Aug 14, 2018.

  1. Hey!

    I am trying to set an ItemStack's lore to an ArrayList<String>

    What I am trying to do is replace each line of the ArrayList<String> with a ChatColor.translateAlternateColorCodes so that the lore can be coloured without me having to put the translateAlternateColorCodes when adding to the ArrayList<String>

    I am getting the error:
    Code (Text):
    Caused by: java.util.ConcurrentModificationException
     
    My code that I tried is:
    Code (Text):
    if (lore != null && !lore.isEmpty()) {
                Iterator iterator = lore.iterator();
                while (iterator.hasNext()) {
                    String loreLine = iterator.next().toString();
                    lore.remove(loreLine);
                    lore.add(ChatColor.translateAlternateColorCodes('&', loreLine));
                }
            }
    Any help is appreciated. Thanks.
     
  2. You're removing one element while looping that's the error
     
  3. Try
    Code (Java):
    if (lore != null && !lore.isEmpty()) {
                Iterator iterator = lore.iterator();
                ArrayList<String> list = new ArrayList<>();
                while (iterator.hasNext()) {
                    String loreLine = iterator.next().toString();
                    list.add(ChatColor.translateAlternateColorCodes('&', loreLine));
                }
                lore=list;
            }
     
    • Like Like x 1
    • Agree Agree x 1
  4. I would convert the list to a string array and loop through all the strings in it. Something like this.
    Code (Java):
    String[] lore = ...;
    for (int i = 0; i < lore.length; i++) {
        lore[i] = Chatcolor.translate...('&', lore[i]);
    }
    Then convert it back to an arraylist and set the lore.
     
    • Like Like x 1
  5. I'd rather prefer
    Code (Java):
    ArrayList<String> lore;
            for(int i=0; i<lore.size();i++) {
                String inColor = lore.get(i);
                lore.set(i, ChatColor.translateAlternateColorCodes('&', inColor));
            }
    Easy peasy lemon squeezy
     
    • Like Like x 1

  6. Thanks alot. All of your solutions work perfectly.
     
    • Like Like x 1
    • Agree Agree x 1
    • Friendly Friendly x 1
  7. lolz
    Code (Text):

    return lore.stream()
    .map(entry -> ChatColor.translateAlternateColorCodes('&', entry))
    .collect(Collectors.toList());
     
     
    • Agree Agree x 1
  8. looks awful and breaks the solid rules