Java - Streams

From My Limbic Wiki
Revision as of 17:10, 18 October 2019 by Fukakai (talk | contribs) (→‎Samples)

Collections

Main Methods

<source lang="Java"> - add(Object o) //Adds the specified object to the collection. - remove(Object o) //Removes the specified object from the collection. - clear() //Removes all elements from the collection. - size() //Returns an integer that indicates how many elements are currently in the collection. - iterator() //Returns an object that can be used to retrieve references to the elements in the collection. </source>

Samples

Print all Students name

<source lang="Java"> Student student; Iterator iterator = collection.iterator(); while (iterator.hasNext()) {

   student = (Student)(iterator.next());
   System.out.println(student.getFullName());

} </source>

Get a Student

<source lang="Java"> Student student = getNextStudent(); while (student != null) {

   collection.add(student);

} </source>

Iteration Without Generics Often Requires Casting

<source lang="Java"> Student student; Iterator iterator = collection.iterator(); while (iterator.hasNext()) {

   student = (Student)(iterator.next());
   System.out.println(student.getFullName());

} </source>

Autoboxing

is the process of performing the encapsulation before a primitive is stored in a collection, and the following is an example of how this can improve your code: <source lang="Java"> Random random = new Random(); Collection<Integer> collection = new ArrayList<Integer>(); for (int i = 0; i < 10; i++) {

   collection.add(random.nextInt());

} </source>

Unboxing

is the process of extracting the primitive value from its corresponding wrapper object when retrieving data from a collection: <source lang="Java"> int total = 0; Iterator<Integer> iterator = collection.iterator(); while (iterator.hasNext()) {

   total += iterator.next();

} </source>

A voir

  • Parallel stream