Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/372.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
LinkedList中出现的Java反复打印_Java_List - Fatal编程技术网

LinkedList中出现的Java反复打印

LinkedList中出现的Java反复打印,java,list,Java,List,我正在使用Collections.frequency计算一个单词在链接列表中的出现次数,但是因为它在for循环中,所以它会根据找到该单词的次数重新打印出现次数 例如,如果我在列表中添加两次“test”,并打印它将打印的事件 test:2 test:2 我需要把它移出for循环还是什么 String word = textField.getText().toLowerCase(); for(String y : wordList) { if(y.contains(word)) {

我正在使用Collections.frequency计算一个单词在链接列表中的出现次数,但是因为它在for循环中,所以它会根据找到该单词的次数重新打印出现次数

例如,如果我在列表中添加两次“test”,并打印它将打印的事件

test:2
test:2
我需要把它移出for循环还是什么

String word = textField.getText().toLowerCase();
for(String y : wordList) {
   if(y.contains(word)) {
      System.out.println(y + " Occured: " + Collections.frequency(wordList,y) + " times");
    }
}

但是我想不使用set

use count变量而保持LinkedList的使用,并在for循环之外打印它的值。 e、 g


您不需要使用循环。仅使用Collections.frequency使用对象(word)就足够了:

List<String> wordList = new LinkedList<>();
wordList.add("test");
wordList.add("hello");
wordList.add("test");
wordList.add("world");
wordList.add("test");
wordList.add("hello");
wordList.add("test");
wordList.add("hello");

String word = "test";

System.out.println(word + " Occured: " + Collections.frequency(wordList,word) + " times");
List wordList=newlinkedlist();
添加(“测试”);
添加(“你好”);
添加(“测试”);
添加(“世界”);
添加(“测试”);
添加(“你好”);
添加(“测试”);
添加(“你好”);
字符串word=“test”;
System.out.println(word+“出现:”+集合.频率(wordList,word)+“次数”);
输出:

测试发生:4次


因为你是在比较单词,所以应该是。equalsignorecase因为“Hello”=“Hello”谈论的主题词是什么这只是做一个特定的词,他们想要collection@jthort那不是OP要问的。你说得对,我的朋友mistake@Juan卡洛斯·门多萨:是的,事实上这是正确的。我只是想问一个问题,如果输入的字符串是空的,我想打印列表的大小,所以
if(word==“”){System.out.println(wordList.size)}但它只打印发生的
0`?@godlypython在Java中比较字符串时从不使用==。改用
equals
方法。以获取更多信息。空字符串(“”)的行为与任何其他字符串相同。因此,如果您的列表包含空字符串,那么使用frecuency方法将返回它的出现次数。您的代码是模糊的。为什么同时使用检查子字符串匹配的
String.contains(String)
,以及使用
String.equals(String)
扫描精确匹配的
frequency()
?如果列表中包含字符串
{“smart”、“fart”、“art”、“fart”}
,并且用户输入
“art”
,那么您真的希望输出是
智能发生:1次
放屁发生:2次
艺术发生:1次
?@Andreas实际上我认为应该使用同样的信号,因为“smart”这个词在判断它们是否相同时,是否与“SMART”一词相同word@jthort代码确实调用了
toLowerCase()
,因此可以假定
wordList
中的所有字符串都是小写的。
List<String> wordList = new LinkedList<>();
wordList.add("test");
wordList.add("hello");
wordList.add("test");
wordList.add("world");
wordList.add("test");
wordList.add("hello");
wordList.add("test");
wordList.add("hello");

String word = "test";

System.out.println(word + " Occured: " + Collections.frequency(wordList,word) + " times");