map – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Sun, 23 Jul 2023 08:36:42 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg map – Programmerbay https://programmerbay.com 32 32 Map Interface in Java With Program Example https://programmerbay.com/map-interface-in-java-with-program-example/ https://programmerbay.com/map-interface-in-java-with-program-example/#respond Sun, 23 Jul 2023 08:36:42 +0000 https://programmerbay.com/?p=9490 The Map interface is part of Collection framework, however, it is not a sub-interface of the collection. It deals with and represents a group of objects in key-value pair. In this, keys and values are objects where keys must be unique and values can be duplicated. Each key-value pair is termed as Entry and a set of such entries is known as Map.

Collection Framework

It can be defined as an interface that empowers to store and fetch elements based on a key where a key can not be duplicated and can refer to at most a single value.
Map interface consists its various methods to operate with data. There are more often used methods such as put() method to add an element in a key-value pair, get() method to fetch data based on a key and, remove() method to remove an element.

Point to Remember

1) A map represents data structure that stores data in key-value pair
2) It doesn’t allow duplicate key
3) A key can only be associated to at most single value
4) It accepts null key. Only TreeMap implementation doesn’t allow null

How to create a Map Object?

Map is an interface and its implementation classes can be used to create its object. In below example, we’ve used HashMap.

Map<K,V> map = new HashMap<>();

Method of Maps

MethodExplanation
put(key,value)It adds elements in key value form where key represents identifier and value is the actual data. If one tries to make a duplicate entry, then the old value will be replaced with new one. And returns old data, otherwise null will be returned.
putAll(Map Obj)It adds all the given map data to the calling Map with the same key-value mapping
clear()It clears the map and removes all the enteries
containsKey(key)It check whether the given key present in the map or not, if yes , it would return true otherwise false
containsValue( value)It returns true, if the given value is present with one or more key mappings
entrySet()It returns a Set object representing key-value elements
forEach(action)It enables to iterate key-value enteries one by one until all the enteries iterated
get(key)It returns value associated with the provided key
getOrDefault( key, defaultValue)It returns value associated with the provided key, if it's not present, the provided default value would be returned
isEmpty()It checks whether the given map is empty or not
keySet()It is used to get list of keys present in the map
putIfAbsent(key, value)It adds an element if the given key is not associated with any value in the map and returns null, otherwise existing key value
remove(key)It removes a key-value mapped with the given key
remove( key, value)It removes an entry, provided with the given associated key mapped with the given value only
replace(key, value)It replaces the existing mapping if the given key having a mapping in a map
replace(key, oldValue, newValue)It replaces the existing mapping with the mentioned key, if the targeted key having the old value mapped to it
size()It returns the size of enteries in a map
values()It returns collection object containing all the values in a map

Java Program to demonstrate the basic operations of Map interface

Program:

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class MapExample {
    public static void main(String[] args) {
        // Creating a Map object
        Map<String,String> map  = new HashMap<>();

        // putting enteries in the map
        map.put("p","programmerbay");
        map.put("e","Example");
        map.put("a","Another");

        // Retrieving an element based on a key
        System.out.println("fetching value associated with p "+map.get("p"));


        // Iterating over Map elements

        Set<Map.Entry<String,String>> enteries = map.entrySet();

        for (Map.Entry<String,String> singleEntry:
             enteries) {
            System.out.println(singleEntry);
        }
    }
}

Output:

fetching value associated with p programmerbay
p=programmerbay
a=Another
e=Example

Implementing Classes and Interfaces of Map

There are various implementation classes and sub interfaces of Map interface.

Below are the following sub interfaces:

1) SortedMap

SortedMap is a sub interface of Map that provides a way to specify ordering on its keys. By default, keys are sorted in natural order. Further, with the help of Comparator, one can also specify custom sorting order. Additionally, keys inserted must implement Comparable interface.

2) NevigableMap

NavigableMap extends SortedMap that provides navigation methods to navigate through entries of a Map. Methods like lowerEntry, ceilingEntry, lowerKey, floorKey and higherKey are used for locating entries in a map.

Similar to NavigableSet, NavigableMap can also be traversed in both ascending or descending key order. However, if one considers performance, then ascending operations are faster than descending ones.

Below are the following implementation classes:

1) HashMap

HashMap provides a hash table based implementation to store data in key-value pair. It accepts a single null key and multiple null values. It doesn’t guarantee the order of a map. It uses a hash function to calculate the hash code, based on which the respective element get stored among the buckets. As a result, it serves constant-time performance for operations like adding and fetching data.

2) LinkedHashMap

LinkedHashMap is a subclass of HashMap that represents Hash table and linked list as its underlying data structure. It preserves the order of entries which is maintained and defined by a doubly linked list. In other words, it fetches elements in the same order in which they are previously added. It permits at most one null key.

3) IdentityHashMap

IdentityHashMap is an implementation class of Map interface that uses Hash Table as its underlying data structure. Unlike HashMap, it uses == operator to identify duplicate entries.

4) WeakHashMap

WeakHashMap is a Hash table based implementation where entries get automatically cleaned up by garbage collector when its key reference for a mapped value is no longer exist or in use.

5) TreeMap

TreeMap is a red-black tree based implementation class of Map interface. It stores elements in some specific order of its key. It doesn’t allow null key.

Basic Operations in Map

There are various operations that can be performed on data. Below are some frequently used operations.
1) Adding elements
2) Updating elements
3) Removing elements
4) Iterating over elements
5) Retrieving element

1) Adding elements

put() and putIfAbsent() method can be used to add element in a map. Both methods are used in different situations
put(k,v) : It adds single element to a given map. It returns null, indicating that no key mapping is exist
putAll(Map obj) : It adds all the elements consisting in passed Map Object.
putIfAbsent(k,v) : It is similar to put() method but only adds elements if the given key mapping is not present in the targeted map

Program:

import java.util.HashMap;
import java.util.Map;

public class MapExample {
public static void main(String[] args) {
// Creating a Map object
Map<String,String> map = new HashMap<>();
// putting entries in the map
map.put("p","programmerbay");

// Printing Map elements
System.out.println(map);


Map<String,String> differentMap = new HashMap<>();
differentMap.put("e","example");

// Adding element to Map elements
map.putAll(differentMap);

// Printing Map elements
System.out.println(map);

// putIfAbsent is used to add element
map.putIfAbsent("c","code ");

// Printing Map elements
System.out.println(map);

}
}

Output:

{p=programmerbay}
{p=programmerbay, e=example}
{p=programmerbay, c=code , e=example}

2) Updating elements

put() is also used to update the existing key mapping in a map. It returns old key-value existing mapping if present in the map, otherwise, null. In other words, put() replaces an entry if passed key already is present, otherwise, add-operation is performed.

Program:

import java.util.HashMap;
import java.util.Map;

public class MapExample {
public static void main(String[] args) {
// Creating a Map object
Map<String,String> map = new HashMap<>();
// putting entries in the map
map.put("p","programmerbay");

System.out.println(map);

// updating existing key
map.put("p","updated");

System.out.println(map);

}
}

Output:

{p=programmerbay}
{p=updated}

3) Removing elements

remove() method is used to delete a key value pair from a map. There are various overloaded methods of remove.
remove(k) : It removes a key-value mapped with given key in a map
remove(k,v) : It removes a key-value pair present that matches with provided key and value.

Program:

import java.util.HashMap;
import java.util.Map;

public class MapExample {
public static void main(String[] args) {
// Creating a Map object
Map<String,String> map = new HashMap<>();
// putting entries in the map
map.put("p","programmerbay");

System.out.println(map);

// remove existing key
map.remove("p","programmerbay");

System.out.println(map);

}
}

Output:

{p=programmerbay}
{}

4) Iterating over elements

Enhanced forEach() can be used to iterate over elements. In order to iterate through a map, first one needs to get its all entries using entrySet() method.

Program:

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class MapExample {
    public static void main(String[] args) {
        // Creating a Map object
        Map<String,String> map  = new HashMap<>();
        // putting entries in the map
        map.put("p","programmerbay");
        map.put("c","code");
        map.put("e","example");



        Set<Map.Entry<String,String>> enteries = map.entrySet();

        for (Map.Entry<String,String> singleEntry:
             enteries) {
            System.out.println(singleEntry);
        }
    }
}

Output:

p=programmerbay
c=code
e=example

 

5) Retrieving element

get() method is used to retrieve value associated with a key. It accepts key name based on which the associated value is retrieved.

Program:

import java.util.HashMap;
import java.util.Map;

public class MapExample {
    public static void main(String[] args) {
        // Creating a Map object
        Map<String,String> map  = new HashMap<>();
        // putting entries in the map
        map.put("p","programmerbay");

        System.out.println(map);

        // diplaying value based on key
        System.out.println(map.get("p"));

    }
}

Output:

{p=programmerbay}
programmerbay

 

 

 

]]>
https://programmerbay.com/map-interface-in-java-with-program-example/feed/ 0
What is Java Stream ? Explain with Examples https://programmerbay.com/stream-in-java-8-with-example/ https://programmerbay.com/stream-in-java-8-with-example/#respond Wed, 17 Jun 2020 17:26:41 +0000 https://programmerbay.com/?p=6437 What is a Stream in Java 8?

Another Java 8 important feature, it can be defined as a pipeline through which a collection of objects and primitive data can be streamed through and a set of operations are performed over each object.

streams

In other words, It is used to process a collection of objects. It streams over a sequence of objects from a source ( collection of objects or primitive types ), perform intermediate operations on each and every element of that source and provide the final outcome.
A stream can be accompanied by zero or more intermediate operations.

Points to remember:

– It converts the normal list to a stream
– It is used to process data using filter, map and other, the final output can be collected to form a list

– It doesn’t manipulate original data, instead creates a new stream
– It provides various stream operation such as map, filter and more
– An element in a stream is always traversed exactly once.
– It does the stream lazily as it doesn’t traverse until the terminal operation doesn’t get executed

-It forms a pipeline where intermediate operations and terminal operations are chained together

 

There are two ways in Collection interface to produce a Stream:

stream() -> It returns a sequential stream
parallelStream() ->  Returns a parallel stream. It utilizes the multiple cores of the computer by creating multiple threads to form sub-streams and assigns them given tasks which execute in parallel.

A stream can be split into two operations. An intermediate operation where all the manipulation is done and a terminal which produces the end result.

 

Stream Source or Create a Stream

A source might represent an array, collection and other. Another way is, to create a stream and do the further opertion on that particular stream.

Create Streams

  • Stream.of

A static method that returns a squence of ordered stream.

Stream.of(val1,val2 .. ......)

Code Example :

public class CreateStreams {

    public static void main(String[] args) {
// Creating Stream of Characters
        Stream<Character> characterStream = Stream.of('P', 'R', 'O', 'G', 'R', 'A', 'M', 'M', 'E', 'R', 'B', 'A', 'Y');
// Now Printing it as a word
        characterStream.forEach(singleCharacter -> System.out.print(singleCharacter));
    }
}

Output:

PROGRAMMERBAY

One can also create Stream of array with Stream.of() method.

For example:

public class CreateStreams {

    public static void main(String[] args) {
        String[] stringArr = new String[]{"This", "is", "Example", "of", "Stream"};
        // Creating Stream of Array
        Stream<String> arrayStream = Stream.of(stringArr);
        arrayStream.forEach(singleString -> System.out.print(singleString + " "));
    }
}

Output:

This is Example of Stream
  • List.stream()

In this, a list acts like stream and all the operations are done, just as normal stream.

Code example :

public class CreateStreams {

    public static void main(String[] args) {
        List<String> stringList = new ArrayList<>();
        stringList.add("A");
        stringList.add("list");
        stringList.add("example");
        stringList.add("with");
        stringList.add("Stream");

        stringList.forEach(singleString -> System.out.print(singleString + " "));
    }
}

Output:

A list example with Stream

 

Intermediate Operations

An intermediate operation is an operation that always returns a new stream.

  • Filter()

– It allows us to put conditional checks and filter out specific element or data from the source data in form of a new stream.
– It uses predicate as an argument which always returns a boolean type.

Syntax:

filter(Predicate<? super T> predicate)
  • Map()

– It allows us to manipulate the data source or process the data and get the result from it.

– It maps each element to its corresponding result and provides a new stream.

– It accepts Function as an argument which processes a given input to provide the result.

Syntax:

map(Function<? super T,? extends R> mapper)
  • Sorted

-It sorts a list of elements as per natural order.

-However, one can achieve custom behaviour using Comparator.

Code Example :

public class CreateStreams {

    public static void main(String[] args) {
        List<Integer> integerList = new ArrayList<>();
        integerList.add(5);
        integerList.add(2);
        integerList.add(12);
        integerList.add(1);
        integerList.add(45);
        integerList.add(9);
        integerList.stream().sorted().forEach(System.out::println);
    }
}

Output:

1
2
5
9
12
45

Terminal Operations

A terminal operation is an operation that returns non-stream values such as Optional, object, collection and more.

  • Reduce()

A reduce method performs a certain operation on each element of a given list and produces a single output value. In simple words, it reduces a list to a single output.

-It takes two arguments, first is identity and the second one is Accumulator.

Identity: It resembles the initial value of the reduction operation and acts as a default output if no data exist in the given list.

Accumulator: It is itself a function that takes two parameters, the first one is partial output and the second argument represents the next element of the list.

Code example :

public class CreateStreams {

    public static void main(String[] args) {
        List<Integer> integerList = new ArrayList<>();
        integerList.add(5);
        integerList.add(5);
        integerList.add(15);
        Integer sum = integerList.stream().reduce(0,(initialVal, nextElm) -> initialVal + nextElm );
        System.out.println("Sum  : "+sum);
    }
}

Output :

Sum  : 25
  • Collect 

-It is used to translate a stream into a list.

-It simply consolidates all the processed result and returns a list

Syntax:

collect(Collector<? super T,A,R> collector)

Collecting stream data as an array :

toArray() is used to get an array as output after performing intermediate operations.

Code example: 

public class CreateStreams {
    public static void main(String[] args) {
        List<Integer> integerList = new ArrayList<>();
        integerList.add(5);
        integerList.add(10);
        integerList.add(12);
        integerList.add(15);
        integerList.add(21);
        integerList.add(24);
        Integer[] intArr = integerList.stream().filter(singleElement -> (singleElement % 5 == 0)).toArray(Integer[]::new);
        for (Integer element :
                intArr) {
            System.out.println("Multiples of 5 : " + element);
        }
    }
}

Output:

Multiples of 5 : 5
Multiples of 5 : 10
Multiples of 5 : 15

Collecting stream data as a list :

collect(Collectors.toList()) is used to get a list as output after performing intermediate operations.

Code example: 

public class CreateStreams {

    public static void main(String[] args) {
        List<Integer> integerList = new ArrayList<>();
        integerList.add(5);
        integerList.add(10);
        integerList.add(12);
        integerList.add(15);
        integerList.add(21);
        integerList.add(24);
        List<Integer> intList = integerList.stream().filter(singleElement -> (singleElement % 5 == 0)).collect(Collectors.toList());
        for (Integer element :
                intList) {
            System.out.println("Multiples of 5 : " + element);
        }
    }
}

Collecting stream data as a Map:

collect(Collectors.toMap() is used to get a Map as output after performing intermediate operations.

Code example: 

public class CreateStreams {

    public static void main(String[] args) {
        List<Integer> integerList = new ArrayList<>();
        integerList.add(5);
        integerList.add(10);
        integerList.add(12);
        integerList.add(15);
        integerList.add(21);
        integerList.add(24);
        Map<Integer,Integer> intMap = integerList.stream().filter(singleElement -> (singleElement % 5 == 0)).collect(Collectors.toMap(key -> key / 5 , value -> value));
        System.out.println("Map " + intMap);
    }
}

Output:

Map {1=5, 2=10, 3=15}
  • forEach

-Loop through each element of the given stream. It is a new feature provided in Java 8.

Syntax

forEach(Consumer<? super T> action)

 

 

Filter and forEach program example:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class StreamExample {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList(Arrays.asList(5,10,50,15,30,40));

        list.stream().filter(singleEelement -> (singleEelement > 30)).forEach(element -> System.out.println("All value greater than 30 :- "+element));
    }
}

Output:

All value greater than 30 :-50
All value greater than 30 :-40

Explanation:

Above code,  filter method is creating a stream in which only values that are greater than 30 is present, then after, simply printing it over the screen using forEach() method.

 

Map and Collect program example

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamExample {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList(Arrays.asList(5,10,50,15,30,40));

      List newList =  list.stream().map(singleEelement -> singleEelement+5).collect(Collectors.toList());

    newList.forEach(element -> System.out.println(element));
    }
}

Output:

10
15
55
20
35
45

 

Explanation:

Above code,  map method is creating a stream in which each element is incremented by 5 are present, then after, simply converting it to list.

]]>
https://programmerbay.com/stream-in-java-8-with-example/feed/ 0