如何有效地小写集合的每个元素? [英] How to lowercase every element of a collection efficiently?

查看:194
本文介绍了如何有效地小写集合的每个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

降低List或Set的每个元素的最有效方法是什么?

What's the most efficient way to lower case every element of a List or Set?

我对列表的想法:

final List<String> strings = new ArrayList<String>();
strings.add("HELLO");
strings.add("WORLD");

for(int i=0,l=strings.size();i<l;++i)
{
  strings.add(strings.remove(0).toLowerCase());
}

有更好,更快的方式吗?这个例子对于一个Set怎么样?由于目前没有方法将一个操作应用于Set(或List)的每个元素,是否可以在不创建额外临时Set的情况下完成?

Is there a better, faster way? How would this example look like for a Set? As there is currently no method for applying an operation to each element of a Set (or List) can it be done without creating an additional temporary Set?

这样的事情会很好:

Set<String> strings = new HashSet<String>();
strings.apply(
  function (element)
  { this.replace(element, element.toLowerCase();) } 
);

谢谢,

推荐答案

这似乎是一个相当干净的列表解决方案。它应该允许特定的List实现用于提供一个实现,该实现对于列表的遍历(线性时间)和字符串的替换都是最佳的。

This seems like a fairly clean solution for lists. It should allow for the particular List implementation being used to provide an implementation that is optimal for both the traversal of the list--in linear time--and the replacing of the string--in constant time.

public static void replace(List<String> strings)
{
    ListIterator<String> iterator = strings.listIterator();
    while (iterator.hasNext())
    {
        iterator.set(iterator.next().toLowerCase());
    }
}






这是我能想到的最好的套装。正如其他人所说,由于多种原因,该操作不能在该组中就地执行。小写字符串可能需要放在集合中的不同位置,而不是它要替换的字符串。此外,如果小写字符串与已经添加的另一个小写字符串相同(例如,HELLO和Hello都将产生hello),则根本不会将小写字符串添加到集合中,这将是只被添加到集合中一次)。


This is the best that I can come up with for sets. As others have said, the operation cannot be performed in-place in the set for a number of reasons. The lower-case string may need to be placed in a different location in the set than the string it is replacing. Moreover, the lower-case string may not be added to the set at all if it is identical to another lower-case string that has already been added (e.g., "HELLO" and "Hello" will both yield "hello", which will only be added to the set once).

public static void replace(Set<String> strings)
{
    String[] stringsArray = strings.toArray(new String[0]);
    for (int i=0; i<stringsArray.length; ++i)
    {
        stringsArray[i] = stringsArray[i].toLowerCase();
    }
    strings.clear();
    strings.addAll(Arrays.asList(stringsArray));
}

这篇关于如何有效地小写集合的每个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆