如果列表的数量是固定的,你可以使用 where 函数来过滤项目:
List<SomeModel> filteredList = one.where(item => two.contains(item))
.where(item => three.contains(item)).toList();
所以你的方法是:
List<Fruits> getMatchingList(List<Fruits> one, List<Fruits> two, List<Fruits> three){
return one.where(item => two.contains(item))
.where(item => three.contains(item))
.toList();
}
如果您需要处理越来越多的列表,另一方面,只需使用:
List<Fruits> getMatchingList(List<List<Fruits>> listsToAnalyze){
Map<Fruits,integer> fruitCounter = new Map();
//expand is a method that flattern a list of lists in a single list
listsToAnalyze.expand(element => element).toList().forEach(element => {
//if the element exists, its counter is increased, otherwise is set to 1
fruitCounter.update(element, (count) => count+1, ()=> 1);
}
//remove results with counter < size of the list of lists
//supposing that an item can appear only once in each list, this means
//that the value appeared in all lists
fruitCounter.removeWhere((key,value)=> value<listsToAnalyze.lenght);
return fruitCounter.keys.toList();
}
如果一个项目可以在一个列表中出现多次,请不要展开列表并保留List<Fruit> 以控制在每个循环期间是否已在列表中插入项目。记得在每个新列表中清空地图。
List<Fruits> getMatchingList(List<List<Fruits>> listsToAnalyze){
Map<Fruits,integer> fruitCounter = new Map();
List<Fruits> fruitsInsertedThisRound= new List();
//cycle on each list alone
listsToAnalize.forEach(list => {
fruitsInsertedThisRound.clear(); //ensure that the list is empty at each cycle
list.forEach(el => {
//if the element exists, its counter is increased, otherwise is set to 1
if(!fruitsInsertedThisRound.contains(el){
//fruit still not inserted this round
fruitCounter.update(el, (count) => count+1, ()=> 1);
fruitsInsertedThisRound.add(el); //add the element to the list of inserted fruits
}
}
}
//remove results with counter < size of the list of lists
//this means that the value appeared in all lists
fruitCounter.removeWhere((key,value)=> value<listsToAnalyze.lenght);
return fruitCounter.keys.toList();
}