java - 从arraylist返回字符串
问题描述
假设我有一堂课
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
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.
我怎样才能做到这一点?
解决方案
Well as others suggested in comments this will be much easy when you use a Map rather than ArrayList. But in your case to achieve what you need you can follow the below steps.This will be much easy when you use streams in Java 8.But I will provide a simple solution which you can achieve without streams.
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;
}
}
Now based on the value which contains in the result you can continue your work.If result is null after the iteration it means there is no matching item found.
推荐阅读
- android - 错误:程序类型已存在:com.facebook.ads.Ad
- opencl - 如何将 OpenCL 代码从 FP32 转换为 FP16?
- angularjs - ng2-smart-table 显示对象列表
- python - Seaborn 热图上 y 轴刻度的垂直对齐
- c# - Visual Studio Build 似乎不使用当前项目
- bash - shell 脚本在不同的操作系统中使用设置“-x”显示不同的结果
- r - 在非连续时间序列中找到某个时间范围内的最大值
- ios - 属性字符串下划线不适用于外部字体
- azure - Azure IoT 中心:使用 MQTT 和 SDK 的云到设备消息传递
- ibm-streams - 如何获取 IBM Streams 工具包更新?