Create ArrayList from array

后端 未结 30 1823
遇见更好的自我
遇见更好的自我 2020-11-21 22:29

I have an array that is initialized like:

Element[] array = {new Element(1), new Element(2), new Element(3)};

I would like to convert this

30条回答
  •  渐次进展
    2020-11-21 23:01

    Another Java8 solution (I may have missed the answer among the large set. If so, my apologies). This creates an ArrayList (as opposed to a List) i.e. one can delete elements

    package package org.something.util;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    import java.util.stream.Collectors;
    
    public class Junk {
    
        static  ArrayList  arrToArrayList(T[] arr){
            return Arrays.asList(arr)
                .stream()
                .collect(Collectors.toCollection(ArrayList::new));
        }
    
        public static void main(String[] args) {
            String[] sArr = new String[]{"Hello", "cruel", "world"};
            List ret = arrToArrayList(sArr);
            // Verify one can remove an item and print list to verify so
            ret.remove(1);
            ret.stream()
                .forEach(System.out::println);
        }
    }
    

    Output is...
    Hello
    world

提交回复
热议问题