Friday, November 1, 2019

How To Convert Current To List, Set, Map, Together With Concurrenthashmap Inwards Coffee Viii - Larn Amongst Examples

In Java 8, Stream is 1 of the most of import shape equally it allows a lot of useful functional operations e.g. filter, map, flatmap, etc on a collection of object. Hence, going forrard converting a Collection to Stream, performing operations too and so converting the consequence dorsum to dissimilar Collection classes similar List, Set, too Map volition live on a mutual task. The get-go work of converting Stream to Collection is solved past times Java designer past times direct adding a stream() method on Collection interface, which way all other interfaces too classes which derived from Stream too direct hold this method. Though the minute work of converting a Stream to List, Set, too Map requires or so agreement of Stream API of JDK 8 too that's what yous volition larn inwards this article.

I'll demo yous mensuration past times mensuration illustration but the most of import affair to larn is that Collector interface tin forcefulness out live on used to collect the consequence of Stream to whatever collection classes similar List, Set, Map, too fifty-fifty ConcurrentMap.

It industrial plant alongside a companion collect() method from Stream class. This method accepts a Collector too returns the Collection yous want.  Btw, if yous are simply starting alongside Java programming too so I propose yous to get-go acquire through a comprehensive Java course of education like The Complete Java Masterclass course on Udemy to start on the correct note. It's too 1 of the most up-to-date too comprehensive course.

Ok, So without wasting whatever to a greater extent than time, let's start alongside the work.





1. Stream to List

You tin forcefulness out usage the toList() method of Collectors shape to convert a Stream to List inwards Java 8. Here is an illustration for converting a current of integers to a listing of integers. The current is from or so other listing of Integers.

List<Integer> listOfIntegers            = input.stream().collect(Collectors.toList());

The listing volition comprise the items or elements inwards the same fellowship they appear inwards Stream too duplicates are too allowed. Though the listing implementation is non guaranteed e.g. yous can't await an ArrayList or LinkedList, though if yous desire that tin forcefulness out live on done too we'll run into it shortly.

Btw, if yous are wondering how does the collect method know which type of List to render too so don't worry, they figured it out using fantabulous type inference available to lambda expressions. In short, they know it from the Stream chemical portion equally good type of the consequence expected.


1.1 Stream to ArrayList

In the previous example, nosotros run into that toList() method render a List implementation but in that place is no guarantee over implementation. This may piece of work for most of the cases but inwards many other cases, yous demand concrete implementations e.g. ArrayList. In that case, yous demand to usage the toCollection() method of Collectors class.

This method accepts a Supplier which returns a new, empty Collection of the appropriate type.

ArrayList<Integer> aList          = input.stream()                .collect(Collectors.toCollection(ArrayList::new));

You tin forcefulness out run into that nosotros direct hold passed ArrayList::new to the collection() method because nosotros wanted to accumulate the consequence of Stream into an ArrayList. If yous desire whatever other Collection e.g. Vector, yous tin forcefulness out too locomote past times Vector::new. If yous are wondering what is this code called too so don't worry, it's known equally constructor reference, similar to a method reference.


1.2 Stream to LinkedList

This is quite similar to the previous example. Instead of ArrayList nosotros direct hold converted Stream into a LinkedList too in that place is solely 1 alter required inwards the previous code, instead of ArrayList::new nosotros direct hold passed LinkedList::new to the toCollection() method.

LinkedList<Integer> linkedList             = input.stream()                   .collect(Collectors.toCollection(LinkedList::new));

The returned LinkedList volition comprise all the elements of Stream inwards the same fellowship they appear inwards Stream.  You tin forcefulness out farther see The Complete Java Masterclass course to larn to a greater extent than nearly Stream inwards Java 8.

 Stream is 1 of the most of import shape equally it allows a lot of useful functional operati How to convert Stream to List, Set, Map, too ConcurrentHashMap inwards Java 8 - Learn alongside Examples



2. Stream to Set

You tin forcefulness out convert a Stream to Set past times using the Collectors.toSet() method. Since Set doesn't allow duplicates too doesn't supply whatever ordering guarantee, whatever duplicate elements from Stream are lost too ordering is too gone.

Set<Integer> aSet = input.stream().collect(Collectors.toSet());

There are no implementation guarantees provided for the Set returned past times collect method here. You can't assume it a HashSet, but it volition something which implements Set interface. Also, the size of Set volition live on less than or equal to a discover of elements inwards the concluding Stream because duplicate elements are lost when yous covert Stream to Set.


2.1 Stream to HashSet

If yous demand a HashSet rather than a Set too so yous demand to usage the toCollection() method rather than the toSet() method. As nosotros direct hold seen inwards the instance of ArrayList, the toCollection() method allows yous to specify which type of Collection shape yous desire past times providing a supplier. Here is an illustration for converting Stream to HashSet inwards Java.

HashSet<Integer> anHashSet            = input.stream()                   .collect(Collectors.toCollection(HashSet::new));

As alongside whatever other Set, when yous convert Stream to HashSet, all duplicate elements volition live on lost too fellowship of elements volition live on gone.



2.2 Stream to LinkedHashSet

Similar to HashSet, yous tin forcefulness out too usage toCollection() method of Collectors shape to convert a Stream to LinkedHashSet inwards Java. The primary divergence betwixt HashSet too LinkedHashSet is that fellowship is preserved. Elements inwards the LinkedHashSet exists inwards the fellowship they are inserted. Btw, If yous are interested inwards learning to a greater extent than differences yous tin forcefulness out run into my before article HashSet vs LinkedHashSet inwards Java.

LinkedHashSet<Integer> aLinkedHashSet               = input.stream()                      .collect(Collectors.toCollection(LinkedHashSet::new));

Again, similar whatever other Set, duplicate elements from Stream volition live on lost, thus the size of the LinkedHashSet volition live on less than or equal to the discover of elements inwards the concluding Stream.


2.3 Stream to TreeSet

Similar to before examples, yous tin forcefulness out too usage the toCollection() method of Collectors shape to convert a Stream to TreeSet inwards Java. Though, yous should retrieve that TreeSet is a sorted Set too keeps the elements inwards their natural fellowship or a custom fellowship specified past times Comparator.

TreeSet<Integer> aTreeSet          = input.stream()                 .collect(Collectors.toCollection(TreeSet::new));

In this example, elements inwards the TreeSet volition live on inwards their sorted fellowship which may live on dissimilar from their fellowship inwards Stream. Again, whatever duplicate chemical portion volition live on lost because TreeSet doesn't allow duplicate too thus the size of TreeSet will live on less than or equal to the size of the concluding Stream.

If yous are interested to larn to a greater extent than nearly dissimilar collection classes too how to piece of work alongside them using Stream, see books)
  • 20 Examples of Date too Time inwards Java 8 (tutorial)
  • How to convert List to Map inwards Java 8 (solution)
  • What is the default method inwards Java 8? (example)
  • How to usage Stream shape inwards Java 8 (tutorial)
  • Difference betwixt abstract shape too interface inwards Java 8? (answer)
  • How to format/parse the engagement alongside LocalDateTime inwards Java 8? (tutorial)
  • How to usage peek() method inwards Java 8 (example)
  • How to usage filter() method inwards Java 8 (tutorial)
  • How to kind the map past times keys inwards Java 8? (example)
  • How to kind the may past times values inwards Java 8? (example)
  • How to bring together String inwards Java 8 (example)
  • 5 Free Courses to larn Java 8 too ix (courses)

  • Thanks a lot for reading this article so far. If yous similar these Stream to Collection similar List, Set too Map examples too so delight portion alongside your friends. If yous direct hold whatever feedback or dubiousness too so delight drib a note.

    P. S. - If yous are looking for or so complimentary courses to larn novel concepts too features introduced inwards Java 8 too so yous tin forcefulness out too banking concern tally out this listing of Free Java 8 courses on FreeCodeCamp. 

    No comments:

    Post a Comment