简体   繁体   English

Java:如何检查字符串是否是任何LinkedList元素的一部分?

[英]Java: How to check if a string is a part of any LinkedList element?

Okay so I have a LinkedList, and I have a String. 好的,我有一个LinkedList,还有一个String。 I want to check if the String is contained within any of the LinkedList elements. 我想检查String是否包含在任何LinkedList元素内。 For example: 例如:

String a = "apple";
String listelement = "a bunch of apples";
LinkedList list = new LinkedList();
list.add(listelement);
if(list.containsany(a){
   System.out.println("Hooray!");
}

Would result in printing "Hooray!" 将导致打印“万岁!”

Obviously list.containsany isn't a real LinkedList method, I'm just using it for this purpose. 显然list.containsany不是一个真正的LinkedList方法,我只是将其用于此目的。

So how can I simulate my example? 那么如何模拟我的示例?

Thanks 谢谢

String a = "apple";
String listelement = "a bunch of apples";
List<String> list = new LinkedList<String>();
list.add(listelement);
for(String s : list){
  if(s.contains(a)){
   syso("yes");
  }
}

This should do it, in order to find a node contains a particular string, you need to iterate through all the nodes. 应该这样做,以便找到包含特定字符串的节点,您需要遍历所有节点。 You can break the loop, if you want only 1 instance. 如果只需要1个实例,则可以中断循环。

Also you want to use Generics. 您也想使用泛型。 Look at the code. 看代码。 otherwise you will have to cast the node to a String. 否则,您将不得不将节点强制转换为字符串。

String a = "apple";
    String listelement = "a bunch of apples";
    LinkedList<String> list = new LinkedList<String>();
    list.add(listelement);
    Iterator<String> li = list.iterator();
    while (li.hasNext()) {
        if (li.next().contains(a)) {
            System.out.println("Hooray!");
        } 
    }

You would have to iterate across the list, and check each node's value to see if it was a string. 您将不得不遍历列表,并检查每个节点的值以查看其是否为字符串。 If you can guarantee that all members of the linked list should be strings, using Java's Generics to force them all to be Strings may help. 如果可以保证链接列表的所有成员都应为字符串,则使用Java的泛型将其全部强制为字符串可能会有所帮助。

     /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication1;

import java.util.LinkedList;

public class JavaApplication1 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        String a = "apple";
        String listelement = "a bunch of apples";
        LinkedList<String> list = new LinkedList<String>();
        list.add(listelement);
        list.add(new String("boogie"));
        for (String s : list) {
            if (s.contains(a)) {
                System.out.println("yes," + s + " contains " + a);
            } else {
                System.out.println("no," + s + " does not contain " + a);
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM