2

我有一个 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"
4

4 回答 4

3

试试这个

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))。

于 2012-12-18T00:50:13.030 回答
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);
于 2012-12-17T23:40:58.383 回答
1

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

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

于 2012-12-17T23:42:20.973 回答
-1
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;
}

希望这会对您有所帮助!

于 2014-09-18T08:59:31.350 回答