【问题标题】:Return string from arraylist从arraylist返回字符串
【发布时间】:2021-02-03 04:27:52
【问题描述】:

假设我有一堂课

public class Ttype{
    
    private String type = "";

    public Ttype(String type) {
        
        this.type = type;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}

我有这个类的数组列表

ArrayList<Ttype> type = new ArrayList<Ttype>();

我在数组列表中添加了一些元素

type.add( new new Ttype("Hello"));
type.add( new new Ttype("Bye"));
type.add( new new Ttype("Hi"));

当我在数组列表中搜索特定字符串时,我希望能够返回一个字符串。我的意思是:

Ttype t = type.get("Hello"); //t will be set to "hello" if hello is in the arraylist.

我该怎么做?

【问题讨论】:

  • 可能是您正在寻找地图而不是数组列表吗? map.put("hello", new Ttype("Hello"));map.get("Hello") //returns a object of type Ttype
  • 我以前从未真正听说过地图。我之前有枚举,其中包含不同的元素。公共类型枚举{嗨,你好,再见}。之前我有过这样的 Types t = Types.Bye;然后他们就无法在任何时候珍惜,例如。如果(t!= types.bye)t = types.hello;我想做类似的事情,但使用arraylist。相反,我有 arraylist type = new Arraylist(); .我想用 arraylist 改变我的整个枚举结构。所以 Ttypes t = type.get("bye") 等等。我不知道我是不是想错了,或者这是一条路要走。
  • 简单:java 集合有列表、集合和映射。你最好了解这些是关于什么的。贾利克是完全正确的。您想为此任务使用简单的地图。
  • 我推荐这个tutorial
  • 这能回答你的问题吗? Searching in a ArrayList with custom objects for certain strings 在发布您的问题之前,您是否尝试过在 Internet 上搜索词 java search arraylist

标签: java arraylist


【解决方案1】:

正如其他人在 cmets 中建议的那样,当您使用 Map 而不是 ArrayList 时,这会容易得多。但是在你的情况下,你可以按照以下步骤来实现你所需要的。当你在 Java 8 中使用流时,这会很容易。但是我将提供一个简单的解决方案,你可以在没有流的情况下实现。

Ttype result = null;//To store if an object found 
String searchTxt = "Hello";

for(Ttype temp:type){//Iterating through the list find a match

   if(temp.type.equlas(searchTxt)){
       result = temp;
   }

}

现在根据结果中包含的值,您可以继续工作。如果迭代后结果为空,则表示没有找到匹配项。

【讨论】:

    【解决方案2】:
    type.stream()
      .filter(c -> c.getType().equals("test"))
      .collect(Collectors.toList());
    
    猜你喜欢
    • 2013-10-25
    • 1970-01-01
    • 2014-08-19
    • 2014-03-14
    • 2012-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多