2

How we can create some Concrete collection type from Stream.collect() method

e.g for below example, I want to Created LinkedList instead of generic List.

List<Integer> list = Arrays.asList(10,20,30,40);
        List<Integer> collect3 = list.stream().filter(i ->i%2==0).collect(Collectors.toList());

How can I specify, I need to create LinkedList

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
Niraj Sonawane
  • 10,225
  • 10
  • 75
  • 104
  • 2
    You got an answer to your question, so you know now how to specify a concrete collection type, however, why do you want a `LinkedList `? There is almost no practical reason to want it. See also [When to use LinkedList over ArrayList?](https://stackoverflow.com/q/322715/2711488)… – Holger Dec 14 '17 at 10:58

1 Answers1

5

You can use a constructor reference, LinkedList::new, and the Collectors.toCollection method.

list.stream().filter(i ->i%2==0).collect(Collectors.toCollection(LinkedList::new))
Alan Effrig
  • 763
  • 4
  • 10