How to lowercase every element of a collection efficiently?

后端 未结 11 548
走了就别回头了
走了就别回头了 2020-12-02 16:53

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

My idea for a List:

final List strings = new ArrayList<         


        
相关标签:
11条回答
  • 2020-12-02 17:41

    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. :)

    0 讨论(0)
  • 2020-12-02 17:44

    This is probably faster:

    for(int i=0,l=strings.size();i<l;++i)
    {
      strings.set(i, strings.get(i).toLowerCase());
    }
    
    0 讨论(0)
  • 2020-12-02 17:46

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

    0 讨论(0)
  • 2020-12-02 17:47

    Yet another solution, but with Java 8 and above:

    List<String> result = strings.stream()
                                 .map(String::toLowerCase)
                                 .collect(Collectors.toList());
    
    0 讨论(0)
  • 2020-12-02 17:47

    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));
    
    0 讨论(0)
提交回复
热议问题