[英]List in Android: Rename duplicated items
I want to create lists as follows: 我要创建列表,如下所示:
As above with list-item , if the item's name is the same in next row, then it will add the suffix 1
. 与上面的list-item一样 ,如果项目的名称在下一行相同,则它将添加后缀
1
。
like this done upto this enter image description here 像这样完成到这里在这里输入图像描述
OK, so you want to ask how to implement this. 好的,所以您想问一下如何实现这一点。 The most simple solution I can think of is using a
Map<String, Int>
to keep track of the item name. 我能想到的最简单的解决方案是使用
Map<String, Int>
来跟踪项目名称。 Your code will look somewhat like this: 您的代码将如下所示:
final Map<String, Integer> listNameMap = new HashMap<String, Integer>();
When displaying a list item name, you'll do: 显示列表项名称时,您将执行以下操作:
final String displayedName;
if (listNameMap.containsKey(name)) {
Integer newValue = listNameMap.get(name).intValue() + 1;
listNameMap.put(name, newValue);
displayedName = name + "-" + String.valueOf(newValue);
} else {
listNameMap.put(name, 0);
displayedName = name;
}
// then use the displayedName to display
i have tried with sample data and below solution worked for me.But there can more efficient solution also. 我已经尝试过使用示例数据,下面的解决方案为我工作。但是也可以有更有效的解决方案。 This solution doesn't require ordering of data.
此解决方案不需要数据排序。
List<String> parent =new ArrayList<String>();
parent.add("R");
parent.add("I");
parent.add("S");
parent.add("R");
parent.add("I");
parent.add("S");
parent.add("R");
parent.add("I");
parent.add("S");
parent.add("R");
parent.add("R");
parent.add("I");
HashSet<String> set = new HashSet<>(parent);
ArrayList<String> valuesList = new ArrayList<>();
valuesList .addAll(set);
Log.d("ValueListWithoutDuplicates",valuesList.size()+"");
int counter = 0;
for(int i=0;i<valuesList.size();i++){
for(int j=0;j<parent.size();j++){
if(valuesList.get(i).equals(parent.get(j))){
if(counter==0){
counter++;
}else {
parent.set(j,parent.get(j)+String.valueOf(counter));
counter++;
}
}
}
counter=0;
}
for(int i=0;i<parent.size();i++){
Log.d("final value",parent.get(i)+"");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.