Showing posts sorted by relevance for query 10-examples-of-hashmap-in-java-programming-tutorial. Sort by date Show all posts
Showing posts sorted by relevance for query 10-examples-of-hashmap-in-java-programming-tutorial. Sort by date Show all posts

Saturday, March 28, 2020

10 Examples Of Hashmap Inwards Coffee - Programming Tutorial

The HashMap inward Java is i of the most pop Collection course of didactics alongside Java programmers. After my article on How HashMap plant inward Java, which describes theory component subdivision of Java HashMap as well as becomes hugely pop alongside Java programmers, I idea to portion how to utilization HashMap inward Java with around key HashMap examples, but couldn't practice that before as well as it was slipped. The HashMap is a information structure, based on hashing, which allows you lot to shop an object every bit a key-value pair, an payoff of using HashMap is that you lot tin recollect object on constant fourth dimension i.e. O(1) if you lot know the key.

The HashMap course of didactics implements Map interface as well as supports Generics from Java 1.5 release, which makes it type safe. There are a brace of to a greater extent than Collections, which provides similar functionalities similar HashMap, which tin besides endure used to shop key value pair.

Hashtable is i of them, but Hashtable is synchronized as well as performs poorly inward a unmarried threaded environment. See Hashtable vs HashMap for consummate differences betwixt them.

Another one, relatively novel is ConcurrentHashMap, which provides amend performance than Hashtable inward a concurrent surroundings as well as should endure preferred. See the difference betwixt ConcurrentHashMap as well as HashMap for exceptional differences.

In this Java tutorial, nosotros volition come across dissimilar examples of HashMap, similar adding as well as removing entries, iterating over Java HashMap, checking size map, finding if a key or value exists on Map as well as diverse other examples, which nosotros used frequently.



Java HashMap Example

Before going to come across these examples, few things to banknote almost Java HashMap.It’s non synchronized, hence don't portion your HashMap alongside multiple threads. 

Another mutual crusade of the mistake is clearing Map as well as reusing it, which is perfectly valid inward a unmarried threaded surroundings but if done inward a multi-threaded surroundings tin create subtle bugs.

Java HashMap Example 1: Create as well as add together objects inward HashMap

In the outset representative of HashMap, nosotros volition create as well as add together an object to our Map. Always utilization Generics, if you lot are non working inward Java 1.4. The next code volition create HashMap with keys of type String as well as values of type Integer with default size as well as charge factor.

HashMap<String, Integer> cache = novel HashMap<String, Integer>();

alternatively, you lot tin create HashMap from copying information from around other Map or Hashtable every bit shown inward below example:
 
Hashtable<Integer, String> root = novel Hashtable<Integer,String>(); HashMap<Integer, String>  map = novel HashMap(source);

You tin besides render charge gene (percentage of size, which if filled trigger resizes of HashMap) as well as initial capacity spell creating an instance past times using overloaded constructor provided inward API.

Adding elements besides called the lay functioning inward HashMap as well as requires a key as well as a value object.

Here is an representative of adding key as well as value inward Java HashMap:

map.put(21, "Twenty One"); map.put(21.0, "Twenty One"); //this volition throw compiler error because 21.0 is not integer

You tin farther see how does get() method internally piece of job inward Java to larn to a greater extent than almost retrieving mapping inward Java. The article explains how get() method uses equals() as well as hashCode() to recollect value object fifty-fifty inward representative of collision.

4 ways to loop HashMap inward Java.

Here is an representative of iterating over Map using java.util.Iterator :

map.put(21, "Twenty One"); map.put(31, "Thirty One");         Iterator<Integer> keySetIterator = map.keySet().iterator();  while(keySetIterator.hasNext()){   Integer key = keySetIterator.next();   System.out.println("key: " + key + " value: " + map.get(key)); }  Output: key: 21 value: Twenty One key: 31 value: Thirty One

You tin besides refer forEach() method inward Java 8.

 inward Java is i of the most pop Collection course of didactics alongside Java programmers 10 Examples of HashMap inward Java - Programming Tutorial


Java HashMap Example 4: Size as well as Clear inward HashMap

Two key examples of HashMap is finding out how many elements are stored inward Map, known every bit the size of Map as well as clearing HashMap to reuse. Java Collection API provides ii convenient methods called size() as well as clear() to perform these operations on java.util.HashMap, hither is code example.

System.out.println("Size of Map: " + map.size()); map.clear(); //clears hashmap , removes all element System.out.println("Size of Map: " + map.size());   Output: Size of Map: 2 Size of Map: 0


You tin reuse Map past times clearing it, but endure careful if it's been shared betwixt multiple threads without proper synchronization. Since you lot may need to preclude other thread from accessing map when it's getting clear. I propose non to practice until you lot receive got a really proficient argue for doing it.


Java HashMap Example five as well as 6: ContainsKey as well as ContainsValue Example

In this representative of Java HashMap, nosotros volition larn how to cheque if Map contains a exceptional object every bit key or value. java.util.HashMap provides convenient methods similar containsKey(Object key) as well as containsValue(Object value) which tin endure used to for checking the beingness of whatever key value inward HashMap.

Here is a code representative :

System.out.println("Does HashMap contains 21 every bit key: " + map.containsKey(21)); System.out.println("Does HashMap contains 21 every bit value: " + map.containsValue(21)); System.out.println("Does HashMap contains Twenty One every bit value: " + map.containsValue("Twenty One"));   Output: Does HashMap contains 21 every bit key: true Does HashMap contains 21 every bit value: false  Does HashMap contains Twenty One every bit value: true



Java HashMap Example 7: Checking if HashMap is empty

In this Map example, nosotros volition larn how to cheque if HashMap is empty inward Java. There are ii ways to honour out if Map is empty, i is using size() method if size is null agency Map is empty.

Another way to cheque if HashMap is empty is using to a greater extent than readable isEmpty() method which returns truthful if Map is empty.

Here is code representative :

boolean isEmpty = map.isEmpty(); System.out.println("Is HashMap is empty: " + isEmpty);  Output: Is HashMap is empty: false



Java HashMap Example 8: Removing Objects from HashMap

Another mutual representative of Java HashMap is removing entries or mapping from Map. The java.util.HashMap provides remove(Object key) method, which accepts key as well as removes mapping for that key.

This method returns zip or the value of the entry, merely removed. You tin besides see how to form HashMap on keys as well as values for a total code example.

Alternatively, you lot tin utilization SortedMap inward Java similar TreeMap. TreeMap has a constructor which accepts Map as well as tin create a Map sorted on the natural guild of key or whatever custom sorting guild defined past times Comparator.

Only affair is key should endure naturally comparable as well as their compareTo() method shouldn't throw an exception. Just to remind at that spot are no Collections.sort() method defined for Map is exclusively for List as well as it’s implementation e.g. ArrayList or LinkedList.

So whatever sorting for Map requires SortedMap or custom code for sorting on either key or value. hither is code representative of sorting HashMap inward Java past times using TreeMap inward the natural guild of keys:

map.put(21, "Twenty One"); map.put(31, "Thirty One"); map.put(41, "Thirty One");  System.out.println("Unsorted HashMap: " + map); TreeMap sortedHashMap = new TreeMap(map);      System.out.println("Sorted HashMap: " + sortedHashMap);   Output: Unsorted HashMap: {21=Twenty One, 41=Thirty One, 31=Thirty One} Sorted HashMap: {21=Twenty One, 31=Thirty One, 41=Thirty One}



Java HashMap Example 10: Synchronized HashMap inward Java

You need to synchronize HashMap if you lot desire to utilization it inward a multi-threaded environment. If you lot are running on Java 1.5 as well as higher upwards consider using ConcurrentHashMap inward house of synchronized HashMap because it provides amend concurrency.

If your projection is nevertheless on JDK 1.4 hence you lot got to utilization either Hashtable or synchronized Map.

The Collections.synchronizedMap(map) is used to synchronize HashMap inward Java. See here for a total code example. This method returns a thread-safe version of Map as well as all map functioning is serialized.


Further Learning
Java In-Depth: Become a Complete Java Engineer
Difference betwixt HashMap as well as ArrayList inward Java
When to utilization Map, List, as well as Set collection inward Java
Difference betwixt HashMap as well as HashSet inward Java
Difference betwixt IdentityHashMap as well as HashMap inward Java

Friday, November 8, 2019

How To Convert Arraylist To Hashmap Or Linkedhashmap Inwards Coffee Viii - Representative Tutorial

One of the mutual occupation inwards Java is to convert a List of object e.g. List<T> into a Map e.g. Map<K, V>, where K is around belongings of the object in addition to V is the actual object. For example, suppose you lot receive got a List<Order> in addition to you lot desire to convert it into a Map e.g. Map<OrderId, Order>, how practise you lot that? Well, the simplest way to attain this is iterating over List in addition to add together each chemical component to the Map past times extracting keys in addition to using the actual chemical component equally an object. This is precisely many of us practise it inwards pre-Java 8 footing but JDK 8 has made it fifty-fifty simpler. In Java 8, you lot tin acquire the flow from List in addition to and then collect all elements into a Map past times using a Collector. The collect() method of Stream course of written report in addition to java.util.stream.Collectors course of written report gives you lot ample choices to create upward one's heed which belongings goes into the primal in addition to which object goes into the value.

Also, In most cases, you lot convert an ArrayList to HashMap or LinkedHashMap, depending upon the scenario, so the occupation of converting a List to Map is genuinely same equally the occupation of converting an ArrayList to HashMap or LinkedHashMap because ArrayList is a List in addition to HashMap is a Map. I'll present you lot an instance of this shortly.

Btw, inwards general, when you lot convert a List to a Map, you lot receive got to kicking the bucket on inwards heed around of the nuisances which come upward from the fact that they are ii dissimilar information construction amongst dissimilar properties.

For example, a List is an ordered collection which allows duplicate elements, but Map doesn't provide whatever ordering guarantee in addition to it doesn't allow duplicate keys (see difference betwixt HashMap, TreeMap, in addition to LinkedHasMap for to a greater extent than details.


Similarly, it may live possible that the List you lot are converting into a Map may incorporate around duplicates, which may non live a occupation inwards the traditional way because when you lot insert an existing primal into the Map, it overwrites the one-time value, which would live the same object inwards instance of duplicate.

But, it does pose a occupation if you lot endeavour to collect duplicate elements from Stream into a Map, without telling Collector how to resolve the necktie (see duplicates.

Enough of theory, now, let's commence coding now.





How to convert ArrayList to HashMap earlier Java 8

This is the classic way to convert a listing to Map inwards Java. We are iterating over List using enhanced for loop in addition to inserting String equally a primal into a HashMap in addition to its length equally a value into HashMap.

This code likewise handles whatever duplicate inwards the listing good because it is using the put() method to insert entries which override values inwards instance of duplicate keys but no mistake or exception is thrown.

Map<String, Integer> map = novel HashMap<>();
for(String str: listOfString){
   map.put(str, str.length());
}

In this code, I receive got chosen a HashMap but you lot are gratis to direct whatever form of map e.g. LinkedHashMap or TreeMap depending upon your requirement.

You tin fifty-fifty exercise a ConcurrentHashMap, if you lot desire to,  Btw, You should exercise a LinkedHashMap if you lot desire to save companionship though.




Converting ArrayList to HashMap inwards Java 8 using a Lambda Expression

This is the modern way of converting a listing to map inwards Java 8. First, it gets the flow from the list in addition to and then it calls the collect() method to collect all chemical component using a Collector. We are passing a toMap() method to tell Collector that exercise Map to collect element.

Map<String, Integer> map8 = listOfString.stream().collect(toMap(s -> sec , sec -> s.length()));

The starting fourth dimension declaration of toMap is a primal mapper in addition to minute is a value mapper. We are using lambda expression which agency top chemical component itself equally a key (s -> s) in addition to it's length equally value (s -> s.length), here, s represents the electrical flow chemical component of Stream, which is String, thus nosotros are able to telephone telephone the length() method.

The Lambda is really skillful at type inference, you lot tin see method reference because it makes your code cleaner. Lambda is cipher but code in addition to if you lot already receive got a method which does the same matter in addition to then you lot tin top the method reference instead of a lambda expression, equally shown here.

HashMap<String, Integer> hash = listOfString.stream()                                                                 .collect(toMap(Function.identity(), String::length, (e1, e2) -> e2, HashMap::new));

You tin come across hither nosotros are passing Function.identity() instead of passing the value itself, but, nosotros are using HashMap, which agency the companionship volition non live guaranteed, See the difference betwixt HashMap in addition to LinkedHashMap for to a greater extent than details.


Converting ArrayList to LinkedHashMap inwards Java 8

LinkedHashMap<String, Integer> linked = listOfString.stream()
.collect(toMap(
Function.identity(),
String::length,
(e1, e2) -> e2,
LinkedHashMap::new));
System.out.println("generated linkedhashmap:" + linked);
}

}

In this case, nosotros are using LinkedHashMap instead of HashMap, which agency the companionship of elements volition live the same equally inwards List because of LinkedHashMap preserver the insertion order. See The Complete Java MasterClass,  i of the comprehensive Java course of written report from Udemy.




Java Program to convert List to Map inwards JDK 8

Earlier I wanted to exercise a user or domain object similar Order or Book to demonstrate this example, but I decided against it inwards favor of String to kicking the bucket on the plan simple. Since almost every Java developer knows nearly String, it makes the plan much to a greater extent than acceptable in addition to focus remains entirely on Java 8 features.

So, nosotros receive got a list of String in addition to we'll generate a map of String keys in addition to their length equally value, sounds interesting right, good it is.

We'll progressively motion from traditional, iterative Java solution to advanced, functional Java 8 solution, starting amongst the lambda expressions in addition to moving to method reference in addition to dealing amongst to a greater extent than practical scenarios similar converting listing amongst duplicate objects in addition to keeping the companionship of elements intact inwards generated map.


import static java.util.stream.Collectors.toMap;  import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.function.Function;  /*  * Java Program to convert a List to Map inwards Java 8.  * We'll convert an ArrayList of String to an HashMap  * where primal is String in addition to value is their length  */ public class Demo {    public static void main(String[] args) throws Exception {      // an ArrayList of String object     List<String> listOfString = new ArrayList<>();     listOfString.add("Java");     listOfString.add("JavaScript");     listOfString.add("Python");     listOfString.add("C++");     listOfString.add("Ruby");      System.out.println("list of string: " + listOfString);      // converting ArrayList to HashMap earlier Java 8     Map<String, Integer> map = new HashMap<>();     for (String str : listOfString) {       map.put(str, str.length());     }      System.out.println("generated map: " + map);      // converting List to Map inwards Java 8 using lambda expression     Map<String, Integer> map8 = listOfString.stream().collect(         toMap(s -> s, sec -> s.length()));      System.out.println("generated map: " + map);      // using method reference     map8 = listOfString.stream().collect(         toMap(Function.identity(), String::length));      // convert listing amongst duplicate keys to HashMap     listOfString.add("Java");     System.out.println("list of string amongst duplicates: " + listOfString);     HashMap<String, Integer> hash = listOfString.stream()         .collect(             toMap(Function.identity(), String::length, (e1, e2) -> e2,                 HashMap::new));     System.out.println("generated hashmap:" + hash);      // kicking the bucket on the companionship same equally master listing piece conversion     LinkedHashMap<String, Integer> linked = listOfString.stream().collect(         toMap(Function.identity(), String::length, (e1, e2) -> e2,             LinkedHashMap::new));     System.out.println("generated linkedhashmap:" + linked);   }  }  Output: listing of string: [Java, JavaScript, Python, C++, Ruby] generated map: {Java=4, C++=3, JavaScript=10, Ruby=4, Python=6} generated map: {Java=4, C++=3, JavaScript=10, Ruby=4, Python=6} listing of string amongst duplicates: [Java, JavaScript, Python, C++, Ruby, Java] generated hashmap:{Java=4, C++=3, JavaScript=10, Ruby=4, Python=6} generated linkedhashmap:{Java=4, JavaScript=10, Python=6, C++=3, Ruby=4}

From the output, you lot tin come across that the starting fourth dimension generated map has lost the order, inwards listing Ruby comes terminal but inwards the map, Python came last.

Same is truthful for the minute instance because nosotros are non specifying which type of Map we desire to Collectors, thus it is returning a Map implementation which doesn't provide whatever ordering guarantee (see list contains duplicate elements, Java came twice earlier quaternary instance but Map doesn't incorporate duplicate in addition to it didn't throw whatever exception or mistake either because nosotros receive got provided a merge portion to toMap() method to direct betwixt duplicate values.


Important points:

1) You tin exercise the Function.identity() portion if you lot are passing the object itself inwards the lambda expression. For example, lambda appear s -> s tin live replaced amongst Function.identity() call.

2) Use the static of import characteristic to import static methods of Collectors e.g. toMap(), this volition simplify your code.

3) The toMap(keyExtractor, valueExtractor) doesn't provide whatever guarantee of what form of map it volition return.

4) If your List contains duplicate elements in addition to you lot are using them equally the primal in addition to then you lot should exercise toMap(keyMapper, valueMapper, mergeFunction). The merge portion used to resolve collisions betwixt values associated amongst the same key, equally supplied to Map.merge(Object, Object, BiFunction). See Java SE 8 for Really impatient to acquire to a greater extent than nearly merge() portion of Map interface inwards Java 8.

 One of the mutual occupation inwards Java is to convert a List of object e How to convert ArrayList to HashMap or LinkedHashMap inwards Java 8 - Example Tutorial


5) If you lot desire to maintain the companionship of entries inwards the Map same equally inwards the master listing in addition to then you lot should exercise the toMap(keyMapper, valueMapper, mergeFunction, mapSupplier) method, where mapSupplier is a portion which returns a new, empty Map into which the results volition live inserted. You tin provide LinkedHashMap::new using constructor reference to collect consequence inwards a LinkedHashMap, which guarantees the insertion order.


6) Replace lambda appear amongst method reference for brevity in addition to simplified code.


That's all nearly how to convert a List to Map inwards Java 8, peculiarly an ArrayList to HashMap in addition to LinkedHashMap. As I said, it's pretty slowly to practise that using flow in addition to collector.

The Collectors, which is a static utility course of written report similar to Collections, provide several options to collect elements of a flow into the dissimilar type of collection in addition to the toMap() method tin live used to collect elements into a Map.

Though this method is overloaded in addition to past times default doesn't guarantee which type of Map it volition render e.g. HashMap, TreeMap, or LinkedHashMap, you lot require to tell him nearly that.

Similarly, you lot likewise receive got to live mindful of ordering in addition to duplicate elements. If you lot desire the companionship of elements should live the same equally they are inwards the master listing in addition to then you lot should exercise LinkedHashMap equally an accumulator to collect mappings. Similarly, exercise the toMap() version which allows you lot to bargain amongst duplicate keys.


Other Java 8 articles in addition to tutorials you lot may similar to explore

Thanks for reading this article so far. If you lot genuinely similar this tutorial in addition to my tips in addition to then delight part amongst your friends in addition to colleagues. If you lot receive got whatever query or feedback in addition to then delight drib me a note.

P.S.- If you lot simply desire to acquire to a greater extent than nearly novel features inwards Java 8 in addition to then you lot tin likewise come across this listing of Free Java 8 Courses on FreeCodeCamp. It explains all the of import features of Java 8 similar lambda expressions, streams, functional interfaces, Optional, novel Date Time API in addition to other miscellaneous changes.

10 Examples Of Flow Inwards Coffee Eight - Count + Filter + Map + Distinct + Collect

The Java 8 liberate of Java Programming linguistic communication was a game changer version. It non solely provided about useful method but totally changed the way you lot write programs inward Java. The most of import modify it brings inward the mindset of Java developers was to shout back functional as well as supported that yesteryear providing fundamental features similar lambda facial expression as well as Stream API, which takes wages of parallel processing as well as functional operations similar filter, map, flatMap etc. Since as well as then a lot of Java developers are trying their hands to acquire those major changes similar lambda expression, method reference, novel Date as well as Time classes, as well as to a greater extent than importantly, Stream API for volume information operations.

In my opinion, the best way to acquire whatever novel characteristic or functionality is yesteryear writing brusk examples as well as agreement them inward depth. I learned that way as well as that's what prompts me to write this article. In this Java 8 tutorial, I induce got shared about uncomplicated examples of java.util.Stream package, which you lot tin occupation inward your day-to-day Java programming tasks.

Streams are 1 of the most of import additions on JDK, it allows you lot to leverage other changes similar lambda expression, method reference, functional interface as well as internal iteration introduced via the forEach() method.

Some of the most mutual things nosotros practise alongside Streams are filtering a collection, applying map as well as bring down component subdivision on all elements of the collection as well as taking wages of lazy evaluation, built-in parallelism via parallelStream().

This is yesteryear no agency a consummate gear upwardly of examples you lot demand to original Java 8 Stream API, but it volition innovate alongside fundamental functions as well as encourage you lot to explore yesteryear yourself yesteryear reading Java documentation as well as trying them. You tin too banking concern check out a comprehensive online class similar The Java MasterClass to acquire them inward depth along alongside other Java 8 changes.





1. How to occupation Streams inward Java 8

You tin occupation Streams to practise a lot of things inward Java 8. By the way, this current is a chip dissimilar than your Java IO streams e.g. InputStream and OutputStream. This current provides an elegant lazy evaluation of an expression, as well as it too supports intermediate as well as end operations.

Terminal operations are used to hit a resultant as well as subsequently that, you lot cannot reuse them.

The expert affair close Streams is that they locomote out source collection intact i.e. operations on streams doesn't touching the collection from which streams are obtained. By the way, you lot tin acquire Stream non only from the Collection but from other sources similar Random Number generator as well as FileInputStream.

In fact, current API is a handy abstraction for working alongside aggregated data, especially when nosotros demand to perform multiple actions, such every bit transforming the content, apply about filters as well as mayhap grouping them yesteryear a property.

Since the collection is going to live the starting indicate for a stream, I induce got used List for all my examples. Once you lot know basics, you lot tin too apply it to other Collection classes e.g. HashSet or HashMap.


Now let's come across the code as well as and then nosotros volition utter close each example.

import java.util.Arrays; import java.util.IntSummaryStatistics; import java.util.List; import java.util.stream.Collectors;  /**   * Java programme to demonstrate how to occupation Java 8 Stream API alongside simple   * examples similar filter objects, transforming objects as well as creating subsets.   * @author http://java67.com   */ public class Java8Streams{      public static void main(String args[]) {          // Count the empty strings         List<String> strList = Arrays.asList("abc", "", "bcd", "", "defg", "jk");         long count = strList.stream()                             .filter(x -> x.isEmpty())                             .count();         System.out.printf("List %s has %d empty strings %n", strList, count);          // Count String alongside length to a greater extent than than 3         long num = strList.stream()                            .filter(x -> x.length()> 3)                            .count();         System.out.printf("List %s has %d strings of length to a greater extent than than 3 %n",                              strList, num);                     // Count give away of String which startswith "a"         count = strList.stream()                        .filter(x -> x.startsWith("a"))                        .count();         System.out.printf("List %s has %d strings which startsWith 'a' %n",                                strList, count);               // Remove all empty Strings from List         List<String> filtered = strList.stream()                                        .filter(x -> !x.isEmpty())                                        .collect(Collectors.toList());         System.out.printf("Original List : %s, List without Empty Strings : %s %n",                                        strList, filtered);               // Create a List alongside String to a greater extent than than 2 characters         filtered = strList.stream()                           .filter(x -> x.length()> 2)                           .collect(Collectors.toList());         System.out.printf("Original List : %s, filtered listing : %s %n", strList, filtered);                     // Convert String to Uppercase as well as bring together them using coma         List<String> G7 = Arrays.asList("USA", "Japan", "France", "Germany", "Italy",                                            "U.K.","Canada");         String G7Countries = G7.stream()                                .map(x -> x.toUpperCase())                                .collect(Collectors.joining(", "));         System.out.println(G7Countries);               // Create List of foursquare of all distinct numbers         List<Integer> numbers = Arrays.asList(9, 10, 3, 4, 7, 3, 4);         List<Integer> distinct = numbers.stream()                                          .map( i -> i*i).distinct()                                          .collect(Collectors.toList());         System.out.printf("Original List : %s,  Square Without duplicates : %s %n",                                           numbers, distinct);               //Get count, min, max, sum, as well as average for numbers         List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);         IntSummaryStatistics stats = primes.stream()                                            .mapToInt((x) -> x)                                            .summaryStatistics();         System.out.println("Highest prime give away inward List : " + stats.getMax());         System.out.println("Lowest prime give away inward List : " + stats.getMin());         System.out.println("Sum of all prime numbers : " + stats.getSum());         System.out.println("Average of all prime numbers : " + stats.getAverage());     }  }  Output: List [abc, , bcd, , defg, jk] has 2 empty strings List [abc, , bcd, , defg, jk] has 1 strings of length to a greater extent than than 3 List [abc, , bcd, , defg, jk] has 1 strings which startsWith 'a' Original List : [abc, , bcd, , defg, jk], List without Empty Strings : [abc, bcd, defg, jk] Original List : [abc, , bcd, , defg, jk], filtered listing : [abc, bcd, defg] USA, JAPAN, FRANCE, GERMANY, ITALY, U.K., CANADA Original List : [9, 10, 3, 4, 7, 3, 4],  Square Without duplicates : [81, 100, 9, 16, 49] Highest prime give away inward List : 29 Lowest prime give away inward List : 2 Sum of all prime numbers : 129 Average of all prime numbers : 12.9


2. Java 8 Stream Examples

Now that you lot induce got seen the code inward action, you lot may induce got figured out that nosotros induce got used a lot of methods from the Stream degree of Java 8 API.

Some of the most prominent methods used inward these examples are the filter() -  which allows elements which gibe the predicate, count() - which counts the give away of elements inward a stream, map() - which applies a component subdivision inward each chemical constituent of Stream for transformation, as well as collect() - which collects the lastly resultant of Stream processing into a Collection.

Now, let's walk through each instance to empathize what they are doing as well as how they are doing.

1. Java 8 Filter Example: Counting Empty String

Here is an instance of counting how many elements are inward the current at whatever phase of pipeline processing using count() method of Stream class.

List<String> strList = Arrays.asList("abc", "", "bcd", "", "defg", "jk"); long count = strList.stream()                      .filter(x -> x.isEmpty())                      .count();

This is a expert instance is to demonstrate how you lot tin filter for sure object from Collection as well as practise a subset of elements which satisfy given criterion. In mo line strList.stream() returns a Stream as well as and then nosotros use the filter() method, which accepts a Predicate.

Since the java.util.function.Predicate is a functional interface ( an interface alongside only 1 abstract method), nosotros tin exceed lambda facial expression instead of an instance of the Predicate interface. Here nosotros tin define code to specify a condition.

This code volition cash inward one's chips to the test() method of Predicate as well as volition live applied to each chemical constituent during internal iteration. All Strings which are empty are counted by count() method, which is a end operation.

After this line, you lot tin non telephone telephone whatever method on this Stream. Remember filter() is a tricky method, it does non filter chemical constituent from the original collection, instead, it selects chemical constituent which satisfies criterion as well as returns them inward novel Collection.

You tin read to a greater extent than close that inward this excellent type inference, that's why in 1 lawsuit you lot specify type parameter inward List, no demand to declare it again, Java 8 volition infer it from there.

This is the argue you lot tin telephone telephone all method of java.lang.String on variable x, whose type was non declared within lambda expression.


3. Java 8 Filter Example 3: Count give away of String which starts alongside "a"

This instance is too precisely similar to the previous ii examples, the solely affair which is dissimilar is the status nosotros are passing to filter method. In the get-go example, nosotros filter empty string, inward the mo instance nosotros filter string whose length has to a greater extent than than five characters as well as inward this example, nosotros are filtering String which starts alongside the missive of the alphabet "a".

By doing all iii examples, you lot should experience to a greater extent than comfortable with the filter() method. 

long count = strList.stream()                     .filter(x -> x.startsWith("a"))                     .count();



This is at in 1 lawsuit the measure technique to filter elements inward Java Collection. You tin specify arbitrary whatever status on lambda facial expression to declare filtering logic.

For example, inward this code, nosotros are creating a subset of String which is starting alongside "a" as well as and then counting them yesteryear using count() method.  If you lot are non familiar alongside basic String materials as well as Java Collection framework, I propose you lot to get-go cash inward one's chips through The Complete Java MasterClass on Udemy, 1 of the best class to acquire Java. It is too updated for Java eleven recently.

 liberate of Java Programming linguistic communication was a game changer version 10 Examples of Stream inward Java 8 - count + filter + map + distinct + collect



4. Java 8 Collectors Example: Remove all empty Strings from List

Now, this instance is a picayune chip dissimilar than the previous three. Here nosotros are over again using filter() method to practise a subset of all string which is non-empty but instead of counting, nosotros are at in 1 lawsuit calling static utility method Collectors.toList() to render them every bit List. 

List<String> filtered = strList.stream()                                .filter(x -> !x.isEmpty())                                .collect(Collectors.toList());

The Collectors degree is really similar to the java.util.Collections class, total of static methods, which you lot tin occupation along alongside Collection. You tin wind filtered elements into a Set or List yesteryear using Collectors class.



5. Java 8 Collectors Example 2: Create a List alongside String to a greater extent than than 2 characters

In this example, ware over again using the filter() method as well as Collectors class, but our filtering criterion is different. 

List<String> filtered = strList.stream()                                .filter(x -> x.length()> 2)                                .collect(Collectors.toList());

After doing this example, you lot should live comfortable alongside creating a subset from the original collection.




6. Java 8 Map functional Example: Convert String to upper-case missive of the alphabet as well as Join them alongside coma

So far nosotros induce got seen examples of only filter() method, inward this example, nosotros volition acquire how to use map() function. 

List<String> G7 = Arrays.asList("USA", "Japan", "France", "Germany",                                         "Italy", "U.K.","Canada"); String G7Countries = G7.stream()                        .map(x -> x.toUpperCase())                        .collect(Collectors.joining(", ")); 

This is similar to the Map concept of functional programming paradigm, similar hither nosotros are converting each String to upper instance as well as and then finally nosotros induce got joined all String using the Collectors.joining(",") method, about other utility method from Java 8 which tin bring together String yesteryear using given delimiter.

If you lot desire to acquire to a greater extent than close what precisely has been changed inward Java 8 along alongside lambdas, Stream, as well as functional programming, map() method, hither nosotros are mapping each chemical constituent to their foursquare as well as and then filtering out all duplicate elements yesteryear calling distinct() method. 

List<Integer> numbers = Arrays.asList(9, 10, 3, 4, 7, 3, 4); List<Integer> distinct = numbers.stream()                                 .map( i -> i*i)                                 .distinct()                                 .collect(Collectors.toList());

Finally yesteryear using the collect() method nosotros are gathering output into a List.




8. Java 8 Statistics Example: Get count, min, max, sum, as well as the average for numbers

This our lastly instance of Stream API, inward this instance nosotros volition acquire how to acquire about statistical information from Collection e.g. finding the minimum or maximum give away from List, calculating the total of all numbers from a numeric listing or calculating the average of all numbers shape List. 

List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29); IntSummaryStatistics stats = primes.stream()                                    .mapToInt((x) -> x)                                    .summaryStatistics();

Since this statistics operations are numeric inward nature, it's of import to telephone telephone mapToInt() method. After this, nosotros telephone telephone the summaryStatistics(), which returns an instance of an IntSummaryStatistics.

It is this object which provides us utility method similar getMin(), getMax(), getSum() or getAverage().

By using these full general purpose methods, you lot tin easily practise a lot of things which require a lot of code earlier Java 8.


That's all close how to occupation Stream API inward Java 8. I induce got barely scratched the surface alongside these examples, streams induce got several gems to offer. At really minimum, every Java developer at in 1 lawsuit should know close filtering elements as well as applying map component subdivision to transform them. For farther reading, you lot tin start exploring java.util.stream packet as well as java.util.function package. These ii packages induce got a lot of interesting things to offer.


Further Learning
The Complete Java MasterClass
The Ultimate Java 8 Tutorial
Refactoring to Java 8 Streams as well as Lambdas Online Self- Study Workshop
Top five Java 8 Courses for Programmers
10 Things Java Developers Should Lear inward 2019
10 Tips to cash inward one's chips a ameliorate Java Developer
10 New Features of Java 10 Programmer Should Know
10 DevOps Courses for Java Developers

P.S.: If you lot desire to acquire to a greater extent than close novel features inward Java 8 as well as then delight come across the tutorial What's New inward Java 8. It explains all the of import features of Java 8 e.g. lambda expressions, streams, functional interface, Optional, novel Date as well as Time API as well as other miscellaneous changes.