【问题标题】:Grouping the nested loop elements based on the first iteration variable in Java基于Java中的第一个迭代变量对嵌套循环元素进行分组
【发布时间】:2023-04-08 16:00:01
【问题描述】:

我有 2 个列表,其中一个用于关键字的句子。这个想法是检查句子是否有关键字。并将它们按顺序排列在每个句子的列表中。

如果这里已经提前复制了,我很抱歉。

List <String> sentence= new ArrayList <>();
sentence.add("this is a good dog");
sentence.add("cats drink milk");
sentence.add("Animals are beautiful creatures");

List <String> keyword= new ArrayList <>();
keyword.add("dog");
keyword.add("cats");
keyword.add("beautiful");
keyword.add("good");
keyword.add("are");
keyword.add("this");
keyword.add("milk");

我的想法是为每个列表创建 2 个嵌套循环:

for (int b = 0; b < sentence.size(); b++) {
    for (int c = 0; c < keyword.size(); c++) {
        if (sentence.get(b).contains(keyword.get(c))) {
            System.out.println(keyword.get(c));
        }
    }
}

这个的输出是:

dog
good
this
cats
milk
beautiful
are

期望的输出是:

[this,good,dog]
[cats,milk]
[are,beautiful]

所以这就像获取所有现有的关键字,按句子的顺序,与关键字顺序无关。

然后按照存在的顺序对每个句子的现有关键字进行分组。

希望很清楚。真的很感激任何想法。不必遵循相同的方法。

【问题讨论】:

  • 是的,感谢您的建议,我不时将其更改为旧学校。在这种情况下,我会寻找地图。对我来说很有意义,但如果你能提供一个例子,也很好。
  • 使用java.util.ArrayList.contains(Object) 并摆脱嵌套循环

标签: java arrays list


【解决方案1】:

遍历您的 sentence 列表。对于每个句子,遍历您的 keyword 列表。添加在 tempList 中找到的每个找到的关键字,按关键字在句子中的索引对 tempList 进行排序,最后将每个 tempList 添加到列表列表中。示例:

public static void main(String[] args) {
    List <String> sentence= new ArrayList <>();
    sentence.add("this is a good dog");
    sentence.add("cats drink milk");
    sentence.add("Animals are beautiful creatures");

    List <String> keyword= new ArrayList <>();
    keyword.add("dog");
    keyword.add("cats");
    keyword.add("beautiful");
    keyword.add("good");
    keyword.add("are");
    keyword.add("this");
    keyword.add("milk");

    List<List<String>> result = new LinkedList<>();
    for(String sen: sentence){
        List<String> tempList = new ArrayList<>();
        for(String key: keyword){            
            if(sen.contains(key)){
                tempList.add(key);
            }
        }
        tempList.sort(new Comparator<String>() {
                @Override
                public int compare(String o1, String o2) {
                   return sen.indexOf(o1) -  sen.indexOf(o2) ;
                }
        });
        result.add(tempList);
    }
    for(List<String> r : result){
        System.out.println(r);
    }
}

【讨论】:

    【解决方案2】:

    您需要对循环稍作修改

    for (int i = 0; i < sentence.size(); i++) {
        String[] matchArray = new String[sentence.get(i).split(" ").length];
        for (int j = 0; j < keyword.size(); j++) {
            if (sentence.get(i).contains(keyword.get(j))) {
                matchArray[Arrays.asList(sentence.get(i).split(" ")).indexOf(keyword.get(j))] = keyword.get(j);
            }
        }
        List<String> matchList = new ArrayList<String>();
        for(String match: matchArray) {
            if(match != null) {
                matchList.add(match);
            }
        }
        System.out.println(matchList);
    }
    

    为每个句子创建一个大小与句子相同的array(只是为了确保大小)。现在,当找到匹配项时,从句子中获取匹配项的索引并将元素添加到 array 的特定索引。因此,在关键字迭代结束时,如果某些单词不匹配,则数组中的所有匹配项都将具有 null 值。

    现在声明一个新的List 的字符串,将数组中不为空的元素添加到其中。最后打印列表。

    【讨论】:

    • 您需要按照匹配项在句子中的出现顺序对匹配项进行排序。虽然您的方法将为第一句话打印[dog,good,this],但OP希望它是[this,good,dog]
    • 这是一个非常smilar和好的解决方案,但除了顺序应该是句子中的顺序,而不是关键字列表。
    • @Sojimanatsu 代码被维护以保持句子的顺序
    【解决方案3】:

    我认为 Map 会是一个不错的选择。只需将地图的句子键和关键字作为值。以下是相同的代码。

    Map <String, ArrayList<String>> sentences= new HashMap<>();
    sentences.put("this is a good dog", new ArrayList<>());
    sentences.put("cats drink milk", new ArrayList<>());
    sentences.put("Animals are beautiful creatures", new ArrayList<>());
    
    List <String> keyword= new ArrayList <>();
    keyword.add("dog");
    keyword.add("cats");
    keyword.add("beautiful");
    keyword.add("good");
    keyword.add("are");
    keyword.add("this");
    keyword.add("milk");
    
    keyword.forEach(word -> sentences.entrySet().stream()
            .filter(map -> map.getKey().contains(word)).
            forEach(map -> sentences.computeIfAbsent(map.getKey(), key->new ArrayList<>()).add(word)));
    
    sentences.forEach((key, value) -> System.out.println(value));
    

    【讨论】:

    • 需要太多修改。但无论如何我喜欢这个主意。谢谢!
    【解决方案4】:

    试试这样的:

        for (String sen: sentence) {
            System.out.print("[");
            boolean first = true;
            for (String word: sen.split("[\\s\\p{Punct}]")) {
                if (keyword.contains(word)) {
                    if (first) {
                        first = false;
                    } else {
                        System.out.print(",");
                    }
                    System.out.print(word);
                }
            }
            System.out.println("]");
        }
    

    【讨论】:

    • 结果在列表中的期望输出暗示。所以我认为最好从列表中打印结果而不是显式打印','和'[]'
    • @funkyjelly 这就是你在回答中所做的。
    【解决方案5】:

    应该这样做,完全按照您要求的格式打印:

    for (int b = 0; b < sentence.size(); b++) {
         String arr[] = sentence.get(b).split("\\s+");
         List result = new ArrayList<>();
         for (int c = 0; c < arr.length; c++ ) {             
             if (keyword.contains(arr[c])) 
                 result.add(arr[c]);        
         }
         System.out.println(result);
    }
    

    【讨论】:

      【解决方案6】:

      我会使用以下内容:

      for(String currentSentence : sentence) {
          List<String> keywordsInSentence = new ArrayList<>();
          for (String word : currentSentence.split("\\s+")) {
              if (keyword.contains(word)) {
                  keywordsInSentence.add(word);
              }
          }
          System.out.println(keywordsInSentence);
      }
      

      你可以试试here

      (我会将sentence 重命名为sentencessentenceListkeyword 也是如此,否则只会令人困惑)

      如果您需要对关键字执行更多操作而不是立即显示它们,您可以将keywordsInSentence 列表插入到Map&lt;String, List&lt;String&gt;&gt; 中,将System.out.println 替换为map.put(currentSentence, keywordsInSentence)

      【讨论】:

        猜你喜欢
        • 2020-07-19
        • 2023-03-21
        • 1970-01-01
        • 2018-05-14
        • 1970-01-01
        • 1970-01-01
        • 2020-06-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多