【问题标题】:Get unique List elements based on a substring根据子字符串获取唯一的 List 元素
【发布时间】:2012-12-17 23:39:01
【问题描述】:

我有一个 ArrayList(String),其中包含一个格式化日期列表,如下所示:

element 1: "2012-5-1"
element 2: "2012-8-10"
element 3: "2012-12-5"
element 4: "2013-12-21"
element 5: "2013-12-13"
element 6: "2014-5-8"

创建另一个包含唯一年份条目的列表或普通原始数组的最有效/框架方法是什么?例如,我的新列表将包含:

element 1: "2012"
element 2: "2013"
element 3: "2014"

【问题讨论】:

    标签: java android


    【解决方案1】:

    试试这个

    ArrayList<String> yearsOnlylist = new ArrayList<String> ();
    for(String s : elements) {
        String yearExtracted = s.substring(0,4);
        yearsOnlylist.add(yearExtracted);
    }
    

    其中 elements 是扩展形式的日期列表的名称。

    用作目的地列表

     LinkedList<String> yearsOnlylist = new LinkedList<String> ();
    

    而不是ArrayList可以明显提高转换效率(因为在LinkedList中添加是O(1))但是第二次访问特定位置,有效率较低(O(n) vs O(1))。

    【讨论】:

      【解决方案2】:

      只需将它们添加到 Set 并将其转换为列表:

      Set<String> unique = new HashSet<String>();
      for (String element : elements) {
          set.put(element.substring(0,4));
      }
      List<String> uniqueList = new ArrayList<String>();
      uniqueList.addAll(unique);
      

      【讨论】:

        【解决方案3】:

        遍历您的数组列表并获取数组列表每个成员的前 4 个字符的子字符串。

        将该子字符串添加到 HashSet 等集合实现中,这将为您提供所需的内容。

        【讨论】:

          【解决方案4】:
          public List<String> trimmer(List<String> x) {
              Log.e("", Integer.toString(x.size()));
              for (int i = 0; i < x.size(); i++) {
                  String s = x.get(i).toString(); 
                  String a = s.substring(6);
                  Log.e("after trim is?", a);
                  x.remove(i);
                  x.add(i, a);
              }
              // check if the element got added back
              Log.e("Trimmer function", x.get(1));
          
              return x;
          }
          

          希望这会对您有所帮助!

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2023-03-24
            • 2016-07-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多