如何有效地小写集合中的每个元素?

发布于 2024-08-29 04:06:06 字数 579 浏览 2 评论 0原文

将列表或集合中每个元素小写的最有效方法是什么?

我对列表的想法:

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 的情况下完成?

像这样的东西会很好:

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

谢谢,

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

My idea for a List:

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());
}

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?

Something like this would be nice:

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

Thanks,

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

薄荷→糖丶微凉 2024-09-05 04:06:06

另一种解决方案,但使用 Java 8 及更高版本:

List<String> result = strings.stream()
                             .map(String::toLowerCase)
                             .collect(Collectors.toList());

Yet another solution, but with Java 8 and above:

List<String> result = strings.stream()
                             .map(String::toLowerCase)
                             .collect(Collectors.toList());
这样的小城市 2024-09-05 04:06:06

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

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

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

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));
}

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());
    }
}

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));
}
怕倦 2024-09-05 04:06:06

您可以使用 Google Collections 执行此操作:

    Collection<String> lowerCaseStrings = Collections2.transform(strings,
        new Function<String, String>() {
            public String apply(String str) {
                return str.toLowerCase();
            }
        }
    );

You can do this with Google Collections:

    Collection<String> lowerCaseStrings = Collections2.transform(strings,
        new Function<String, String>() {
            public String apply(String str) {
                return str.toLowerCase();
            }
        }
    );
嘿哥们儿 2024-09-05 04:06:06

如果您愿意更改输入列表,这里还有另一种实现它的方法。

strings.replaceAll(String::toLowerCase)

If you are fine with changing the input list here is one more way to achieve it.

strings.replaceAll(String::toLowerCase)

錯遇了你 2024-09-05 04:06:06

好吧,由于两个事实,没有真正优雅的解决方案:

  • Java 中的 String 是不可变的
  • Java 没有给你提供真正好的 map(f, list) 函数函数式语言。

渐近地讲,您无法获得比当前方法更好的运行时间。您必须使用 toLowerCase() 创建一个新字符串,并且您需要自己迭代列表并生成每个新的小写字符串,并将其替换为现有字符串。

Well, there is no real elegant solution due to two facts:

  • Strings in Java are immutable
  • Java gives you no real nice map(f, list) function as you have in functional languages.

Asymptotically speaking, you can't get a better run time than your current method. You will have to create a new string using toLowerCase() and you will need to iterate by yourself over the list and generate each new lower-case string, replacing it with the existing one.

邮友 2024-09-05 04:06:06

这可能更快:

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

This is probably faster:

for(int i=0,l=strings.size();i<l;++i)
{
  strings.set(i, strings.get(i).toLowerCase());
}
稚气少女 2024-09-05 04:06:06

尝试 Commons Collections 中的 CollectionUtils#transform 以获得就地解决方案,或 番石榴中的 Collections2#transform如果您需要实时取景。

Try CollectionUtils#transform in Commons Collections for an in-place solution, or Collections2#transform in Guava if you need a live view.

咋地 2024-09-05 04:06:06

我不认为如果将字符串更改为集合,就可以就地进行操作(无需创建另一个集合)。这是因为您只能使用迭代器或 foreach 循环来迭代 Set,并且不能在这样做时插入新对象(它会引发异常)

I don't believe it is possible to do the manipulation in place (without creating another Collection) if you change strings to be a Set. This is because you can only iterate over the Set using an iterator or a for each loop, and cannot insert new objects whilst doing so (it throws an exception)

柳絮泡泡 2024-09-05 04:06:06

参考已接受的(Matthew T. Staebler)解决方案中的 ListIterator 方法。使用 ListIterator 比这里的方法有什么更好的地方?

public static Set<String> replace(List<String> strings) {
    Set<String> set = new HashSet<>();
    for (String s: strings)
        set.add(s.toLowerCase());
    return set;
}

Referring to the ListIterator method in the accepted (Matthew T. Staebler's) solution. How is using the ListIterator better than the method here?

public static Set<String> replace(List<String> strings) {
    Set<String> set = new HashSet<>();
    for (String s: strings)
        set.add(s.toLowerCase());
    return set;
}
滥情空心 2024-09-05 04:06:06

我一直在寻找类似的东西,但被困住了,因为我的 ArrayList 对象没有声明为 GENERIC 并且它可以作为原始 List 从某处输入对象。我刚刚得到一个 ArrayList 对象“_products”。因此,我所做的如下所述,它对我来说非常有效 ::

List<String> dbProducts = _products;
    for(int i = 0; i<dbProducts.size(); i++) {
        dbProducts.add(dbProducts.get(i).toLowerCase());         
    }

也就是说,我首先使用可用的 _products 并制作了一个 GENERIC 列表对象(正如我得到的那样)仅字符串相同),然后我在列表元素上应用了 toLowerCase() 方法,该方法之前由于非通用 ArrayList 对象而不起作用。

我们这里使用的方法toLowerCase()属于String类。

字符串 java.lang.String.toLowerCase()

不属于 ArrayListObject 类。

如有错误请指正。 JAVA新手求指导。 :)

I was looking for similar stuff, but was stuck because my ArrayList object was not declared as GENERIC and it was available as raw List type object from somewhere. I was just getting an ArrayList object "_products". So, what I did is mentioned below and it worked for me perfectly ::

List<String> dbProducts = _products;
    for(int i = 0; i<dbProducts.size(); i++) {
        dbProducts.add(dbProducts.get(i).toLowerCase());         
    }

That is, I first took my available _products and made a GENERIC list object (As I were getting only strings in same) then I applied the toLowerCase() method on list elements which was not working previously because of non-generic ArrayList object.

And the method toLowerCase() we are using here is of String class.

String java.lang.String.toLowerCase()

not of ArrayList or Object class.

Please correct if m wrong. Newbie in JAVA seeks guidance. :)

奈何桥上唱咆哮 2024-09-05 04:06:06

使用JAVA 8并行流变得更快

List<String> output= new ArrayList<>();
List<String> input= new ArrayList<>();
input.add("A");
input.add("B");
input.add("C");
input.add("D");
input.stream().parallel().map((item) -> item.toLowerCase())
            .collect(Collectors.toCollection(() -> output));

Using JAVA 8 parallel stream it becomes faster

List<String> output= new ArrayList<>();
List<String> input= new ArrayList<>();
input.add("A");
input.add("B");
input.add("C");
input.add("D");
input.stream().parallel().map((item) -> item.toLowerCase())
            .collect(Collectors.toCollection(() -> output));
懵少女 2024-09-05 04:06:06

使用Java8来表示集合中每个元素的小写

List<String> groupNamesList =  new ArrayList<>();
groupNamesList.add("GroupOne");
groupNamesList.add("GroupTwo");
groupNamesList.add("GroupThree");
groupNamesList = groupNamesList.stream().map(groupName -> groupName.toLowerCase()).collect(Collectors.toList());

输出:

[groupone,grouptwo,groupthree]

Have used Java8 streams for lowercase of every element in a Collection.

List<String> groupNamesList =  new ArrayList<>();
groupNamesList.add("GroupOne");
groupNamesList.add("GroupTwo");
groupNamesList.add("GroupThree");
groupNamesList = groupNamesList.stream().map(groupName -> groupName.toLowerCase()).collect(Collectors.toList());

Output:

[groupone,grouptwo,groupthree]
铁憨憨 2024-09-05 04:06:06
private static void getOccuranceCount() {
    List<String> listdemo=Arrays.asList("saradhi","bill","mike","Bill","MIKE");
   
    Map<String, Long> collect = listdemo.stream().map(**String::toLowerCase**).collect(Collectors.groupingBy(e->e,Collectors.counting()));
    System.out.println("collector printing is : "+collect);
}
private static void getOccuranceCount() {
    List<String> listdemo=Arrays.asList("saradhi","bill","mike","Bill","MIKE");
   
    Map<String, Long> collect = listdemo.stream().map(**String::toLowerCase**).collect(Collectors.groupingBy(e->e,Collectors.counting()));
    System.out.println("collector printing is : "+collect);
}
×眷恋的温暖 2024-09-05 04:06:06

对于大写

val originalList = arrayListOf("apple", "banana", "cherry")

val upperCaseList = originalList.map { it.toUpperCase() }

对于小写

>val originalList = arrayListOf("苹果", "香蕉", "樱桃")

val lowerCaseList = originalList.map { it.toLowerCase() }

For UppperCase

val originalList = arrayListOf("apple", "banana", "cherry")

val upperCaseList = originalList.map { it.toUpperCase() }

For LowerCase

val originalList = arrayListOf("Apple", "Banana", "Cherry")

val lowerCaseList = originalList.map { it.toLowerCase() }

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文