我在网站上使用了许多引用资料来构建我的程序,但我现在有点陷入困境。我认为使用迭代器可以完成这项工作。可悲的是,即使我遇到了有迭代器的问题,我也无法找到正确使用它在我的代码上实现它的方法。
我想要,
1. 删除列表fname
中找到的相似元素
2. 计算并添加在 fname
中找到的每个元素的计数
计数器。
请帮助我使用迭代器或任何其他方法来完成上述操作。以下是我的代码,
List<String> fname = new ArrayList<>(Arrays.asList(fullname.split(""))); //Assigning the string to a list//
int count = 1;
ArrayList<Integer> counter = new ArrayList<>();
List<String> holder = new ArrayList<>();
for(int element=0; element<=fname.size; element++)
{
for(int run=(element+1); run<=fname.size; run++)
{
if((fname.get(element)).equals(fname.get(run)))
{
count++;
holder.add(fname.get(run));
}
counter.add(count);
}
holder.add(fname.get(element));
fname.removeAll(holder);
}
System.out.println(fname);
System.out.println(counter);
谢谢。
最佳答案
根据您的问题,您基本上想要:
<强>1。消除给定字符串列表中的重复项
您只需将列表转换为 HashSet (它不允许重复),然后将其转换回列表(如果您希望最终结果是一个列表,以便您可以用它做其他事情...)
<强>2。计算列表中唯一单词的所有出现次数 最快的编码是使用 Java 8 Streams(此处借用的代码:How to count the number of occurrences of an element in a List)
完整代码
public static void main(String[] args) {
String fullname = "a b c d a b c"; //something
List<String> fname = new ArrayList<>(Arrays.asList(fullname.split(" ")));
// Convert input to Set, and then back to List (your program output)
Set<String> uniqueNames = new HashSet<>(fname);
List<String> uniqueNamesInList = new ArrayList<>(uniqueNames);
System.out.println(uniqueNamesInList);
// Collects (reduces) your list
Map<String, Long> counts = fname.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(counts);
}
关于java - 在迭代列表时计算并删除列表中的相似元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44997157/