【问题标题】:checking in List<SelectItem> contain this part of string or not in java检查 List<SelectItem> 是否在 java 中包含这部分字符串
【发布时间】:2015-08-02 21:14:47
【问题描述】:

我有一个数组列表

List<SelectItem> list= new ArrayList<SelectItem>();

list.add(new SelectItem("abcdefg");

我需要检查字符串 "abc" 是否包含或部分 selectItem 对象。

实现这一目标的最佳方法是什么。请提出建议。

【问题讨论】:

  • 你能分享SelectItem类代码吗?
  • 用例是什么?你想达到什么目的?

标签: java list object contains


【解决方案1】:

假设 SelectItem 有一个 getValue() 方法:

List<SelectItem> list= new ArrayList<SelectItem>();
list.add(new SelectItem("abcdefg");

booleand found = false;

for(SelectItem item:list){
  if(item.getValue().contains("abc")){
    found = true;
    // action when found

    // if you only need the first hit use "break;"
  }
}
if(!found){
  System.out.println("'abc'is not found in the selectitems. ");
}

【讨论】:

  • 但我不想遍历列表。他们这样做的方式是否更优雅
  • 循环有什么问题?你认为你还能如何搜索一组项目?如果不查看项目,您将无法知道哪个项目是“正确”的。因此,您需要循环
【解决方案2】:

这假定 SelectItem 类似于 JSF SelectItem,并且 getValue() 返回一个字符串。它也可以应用于 getLabel()(同样的 JSF SelectItem 假设)。

for(SelectItem item : list) {
    if(item.getValue().indexOf("abc") != -1) {
        // you have it
    } else {
        // you don't
    }
}

【讨论】:

    【解决方案3】:

    由于您要查找部分字符串,因此您需要遍历元素以检查其中一个是否包含部分字符串。

    【讨论】:

    • 我们不能通过覆盖 equal 方法来做到这一点。人们说我必须迭代整个列表。我不想要那个
    【解决方案4】:

    Java 8 下更优雅的方式:

    if(list.stream().filter(x -> ( (x.getValue()==null)?false:x.getValue().toString().contains("abc") ) )
                    .findFirst()
                    .isPresent()) {
        // action when found 
    } 
    else {   
        // action when not found 
    }    
    

    【讨论】:

      猜你喜欢
      • 2017-08-29
      • 2013-03-14
      • 2017-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-05
      • 1970-01-01
      • 2014-12-27
      相关资源
      最近更新 更多