简体   繁体   中英

Which method of List should be used to assign two matching words to the value

1.//dart language in Flutter

2.//Which method of list should be used to assign two matching words to the value?

3.//The duplicate value should appear next to its matching value?

//Question: List colour=["peach","red","orange","yellow","white","pink","red","maroon"];

//Answer:

Print ["peach","red","red","orange","yellow","white","pink","maroon"]

There is no 'silver bullet' in List, that is able to solve the task, but it possess several useful methods for the case. There could be several ways to solve the problem. For instance, I'm proposing the remove/insert way:

  List<String> colour = ["peach","red","orange","yellow","white","pink","red","maroon", "pink", "red"];
  for (int i = 0; i < colour.length; i++) {
    int indexOfPossibleDuplication = colour.lastIndexOf(colour[i]);
    if (indexOfPossibleDuplication > i) {
      colour.removeAt(indexOfPossibleDuplication);
      colour.insert(i, colour[i]);
    }
  }
  print(colour); //[peach, red, red, red, orange, yellow, white, pink, pink, maroon]

I deliberately inserted several duplicates to your input example in order to show that the code do the trick in cases, when there is more than one duplication took place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM