Java: making List from primitive array using Stream API

后端 未结 3 1025
名媛妹妹
名媛妹妹 2021-01-14 14:40

I\'m trying to make a List from a primitive array

int[] values={4,5,2,3,42,60,20};
List greaterThan4 =
Arrays.stream(values)
        .filter(v         


        
相关标签:
3条回答
  • 2021-01-14 14:45

    Yes this is because Arrays.stream returns an IntStream. You can call boxed() to get a Stream<Integer> and then perform the collect operation.

    List<Integer> greaterThan4 = Arrays.stream(values)
                                       .filter(value -> value > 4)
                                       .boxed()
                                       .collect(Collectors.toList());
    
    0 讨论(0)
  • 2021-01-14 14:49

    You can change int[] values={4,5,2,3,42,60,20}; to Integer[] values={4,5,2,3,42,60,20}; because currently you are passing an array of primitive type(int) but should you pass array of object i.e. Integer

    0 讨论(0)
  • 2021-01-14 15:00

    You're using an array of primitives for one thing, not Integer. I suggest you use Arrays.asList(T...) like

    Integer[] values={4,5,2,3,42,60,20};
    List<Integer> al = new ArrayList<>(Arrays.asList(values));
    
    0 讨论(0)
提交回复
热议问题