Can a lambda be used to change a List's values in-place ( without creating a new list)?

后端 未结 3 1302
傲寒
傲寒 2021-01-04 00:03

I am trying to determine the correct way of changing all the values in a List using the new lambdas feature in the upcoming release of Java 8 w

相关标签:
3条回答
  • 2021-01-04 00:17
        List<String> list = Arrays.asList("Bob", "Steve", "Jim", "Arbby");
        list.replaceAll(String::toUpperCase);
    
    0 讨论(0)
  • With a popular library Guava you can create a computing view on the list which doesn't allocate memory for a new array, i.e.:

    upperCaseStrings = Lists.transform(strings, String::toUpperCase)
    

    A better solution is proposed by @StuartMarks, however, I am leaving this answer as it allows to also change a generic type of the collection.


    Another option is to declare a static method like mutate which takes list and lambda as a parameter, and import it as a static method i.e.:

    
    mutate(strings, String::toUpperCase);
    

    A possible implementation for mutate:

    @SuppressWarnings({"unchecked"})
    public static  List mutate(List list, Function function) {
        List objList = list;
    
        for (int i = 0; i 

    0 讨论(0)
  • 2021-01-04 00:35

    You seem to have overlooked forEach, which can be used to mutate the elements of a List. Of course, that doesn't cover your use case entirely—it won't help if your elements are immutable or if you want to replace them completely. [edit: the next sentence relates to streams, not to collections as specified in the question] There is a good reason why you can't do those operations: they aren't parallel-friendly (this actually applies to forEach also) and the Stream API strongly discourages the use of sequential-only operations.

    0 讨论(0)
提交回复
热议问题