Friday, October 28, 2022

Java Map size() With Examples

If you want to know how many key-value pair are there in a Map you can use size() method which returns the number of key-value mappings in the map.

Syntax of the size() method is

int size()

Method doesn't take any parameters.

Method returns an int value denoting the number of key-value mappings in the map

size() method Java example

Here we have a HashMap with some key, value pair added. Using size() method we'll get the current size of the map.

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

public class SizeMapDemo {
  public static void main(String[] args) {
    Map<String, String> cityMap = new HashMap<String, String>();
    // Adding elements
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Beijing");
    cityMap.put("5", "Berlin");
    
    int sizeOfMap = cityMap.size();
    System.out.println("Number of entries in the Map: " + sizeOfMap);
  }
}

Output

Number of entries in the Map: 5

That's all for this topic Java Map size() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. removeIf() Method in Java Collection With Examples
  2. Java Map putIfAbsent() With Examples
  3. Java Map replace() With Examples
  4. Difference Between ArrayList And LinkedList in Java
  5. Java Collections Interview Questions And Answers

You may also like-

  1. How to Sort Elements in Different Order in TreeSet
  2. CopyOnWriteArrayList in Java With Examples
  3. Type Wrapper Classes in Java
  4. Why Class Name And File Name Should be Same in Java
  5. Convert String to Char Array in Java
  6. Python First Program - Hello World
  7. ApplicationContextAware And BeanNameAware Interfaces in Spring Framework
  8. What is SafeMode in Hadoop

Thursday, October 27, 2022

removeIf() Method in Java Collection With Examples

In this post we'll see how to use removeIf() method to remove elements from the Collection that satisfy the given condition. The removeIf() method is included in java.util.Collection interface in Java 8. Since it is part of Collection interface so you can use it with Collections like ArrayList, HashSet that implements Collection interface. To use it with HashMap you will have to get a collection view of the Map, since Map doesn't implement Collection interface.


Java removeIf() method syntax

boolean removeIf(Predicate<? super E> filter)

Parameter passed to this method is of type Predicate functional interface, which can be implemented as a boolean-valued function with one argument.

Method returns true if any elements were removed.

Removing elements from ArrayList using removeIf() method

In this example we'll have a list of cities and we'll remove elements from this ArrayList using removeIf() method. In passed Predicate if the condition holds true for any of the elements, then that element is removed from the list.

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

public class RemoveIf {

  public static void main(String[] args) {
    List<String> cityList = new ArrayList<String>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Kolkata");
    cityList.add("Hyderabad");
    cityList.add("Bangalore");
    cityList.add("Mumbai");
    System.out.println("*** List Initially ***");
    System.out.println(cityList);
    cityList.removeIf(p -> p.equalsIgnoreCase("Hyderabad") || 
          p.equalsIgnoreCase("Bangalore"));
    System.out.println("After Removal " + cityList);
  }
}

Output

*** List Initially ***
[Delhi, Mumbai, Kolkata, Hyderabad, Bangalore, Mumbai]
After Removal [Delhi, Mumbai, Kolkata, Mumbai]

Removing elements from HashSet using removeIf() method

You can use removeIf() method with HashSet also to remove elements from the Set based on the passed condition. In the given example condition is to remove cities having name of length more than 6.

import java.util.HashSet;
import java.util.Set;

public class RemoveIf {

  public static void main(String[] args) {
    // creating a HashSet
    Set<String> citySet = new HashSet<String>();
    // Adding elements
    citySet.add("London");        
    citySet.add("Tokyo");
    citySet.add("New Delhi");
    citySet.add("Beijing");
    citySet.add("Nairobi");
    System.out.println("*** Set Initially ***");
    System.out.println(citySet);
    
    // Remove all cities having length more than 6
    citySet.removeIf(e -> e.length() > 6);
    System.out.println("After Removal " + citySet);
  }
}

Output

*** Set Initially ***
[Beijing, New Delhi, Nairobi, Tokyo, London]
After Removal [Tokyo, London]

Removing elements from HashMap using removeIf() method

To use removeIf() method with a Map you have to get Collection view of a Map. After getting the Collection view of a Map removeIf() method can be used.

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


public class RemoveIf {

  public static void main(String[] args) {
    Map<String, String> cityMap = new HashMap<String, String>();
    // Adding elements
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Beijing");
    cityMap.put("5", "Berlin");

    System.out.println("*** Map Initially ***");
    System.out.println(cityMap);
      
    // Use entrySet to get Set view of all Map entries. 
    // Remove entry from Map based on the condition for value.
    cityMap.entrySet().removeIf(entry -> entry.getValue().equals("Beijing"));
    System.out.println("*** Map After removal ***");
    System.out.println(cityMap);
  }
}

Output

*** Map Initially ***
{1=New York City, 2=New Delhi, 3=Mumbai, 4=Beijing, 5=Berlin}
*** Map After removal ***
{1=New York City, 2=New Delhi, 3=Mumbai, 5=Berlin}

That's all for this topic removeIf() Method in Java Collection With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to Remove Entry From HashMap in Java
  2. How to Remove Elements From an ArrayList in Java
  3. How to Remove Duplicate Elements From an ArrayList in Java
  4. Java Map replace() With Examples
  5. HashSet Vs LinkedHashSet Vs TreeSet in Java

You may also like-

  1. Difference Between Comparable and Comparator in Java
  2. CopyOnWriteArraySet in Java With Examples
  3. Switch Expressions in Java 12
  4. Java Nested Class And Inner Class
  5. Reading File in Java Using Files.lines And Files.newBufferedReader
  6. Angular Cross Component Communication Using Subject Observable
  7. Angular HttpClient - Set Response Type as Text
  8. Spring Web MVC Tutorial

Wednesday, October 26, 2022

How to Remove Elements From an ArrayList in Java

To remove elements from an ArrayList in Java you have the following options.

  • You can use remove() method provided by ArrayList class to remove an object from ArrayList.
  • You can use remove() method provided by Iterator.
  • There is a removeIf() method too in ArrayList class that can be used Java 8 onwards to remove elements from ArrayList in Java.

In this post we'll see when to use which method and why.


ArrayList remove() method

ArrayList provides two overloaded remove methods for removing element from an ArrayList in Java-

  • remove(int index)- This method takes int (which specifies the index in the list) as parameter and removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices).
  • public boolean remove(Object o)- This method takes the object, which has to be removed as parameter and removes the first occurrence of the specified element from this list, if it is present. If the list does not contain the element, it is unchanged.

If you are just removing an element from an ArrayList without looping the list then you can remove an element by giving its index in the list or specifying the object itself.

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

public class RemoveFromListDemo {
  public static void main(String[] args) {
    List<String> cityList = new ArrayList<String>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Kolkata");
    cityList.add("Hyderabad");
    cityList.add("Bangalore");
    cityList.add("Mumbai");
    System.out.println("Original List- " + cityList);
    cityList.remove(1);
    
    cityList.remove("Mumbai");
    System.out.println("List after removing elements- " + cityList);
  }
}

Output

Original List- [Delhi, Mumbai, Kolkata, Hyderabad, Bangalore, Mumbai]
List after removing elements- [Delhi, Kolkata, Hyderabad, Bangalore]

Removing element from ArrayList while iterating the list

Note that using ArrayList's remove method with enhanced for loop or iterator may result in ConcurrentModificationException as the iterators returned by ArrayList class's iterator and ListIterator methods are fail-fast. Which means if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.)

Example code

Here is an example where ArrayList's remove() method is used while iterating a list using For-Each loop. As you can see ConcurrentModificationException is thrown.

public class RemoveFromListDemo {
  public static void main(String[] args) {
    List<String> cityList = new ArrayList<String>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Kolkata");
    cityList.add("Hyderabad");
    cityList.add("Bangalore");
    cityList.add("Mumbai");
               
    for(String city : cityList){
      if(city.equalsIgnoreCase("Kolkata"))
        cityList.remove(city);
    }
  }
}

Output

Exception in thread "main" java.util.ConcurrentModificationException
 at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
 at java.util.ArrayList$Itr.next(Unknown Source)
 at org.netjs.prog.RemoveFromListDemo.main(RemoveFromListDemo.java:20)

Using Iterator's remove method to remove element from ArrayList

While looping if you want to remove any element from an ArrayList you should use use Iterator's remove method so that ConcurrentModificationException is not thrown.

public class RemoveFromListDemo {
  public static void main(String[] args) {
    List<String> cityList = new ArrayList<String>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Kolkata");
    cityList.add("Hyderabad");
    cityList.add("Bangalore");
    cityList.add("Mumbai");
                
    Iterator<String> itr = cityList.iterator();
    int i = 0;
    while(itr.hasNext()){
      System.out.println("city " + itr.next());
      if(i == 3 || i == 4){
        itr.remove();
      }
      i++;
    }
    
    System.out.println("After deletion " );
    for(String city : cityList){
      System.out.println("city " + city);
    }
  }
}

Output

city Delhi
city Mumbai
city Kolkata
city Hyderabad
city Bangalore
city Mumbai
After deletion 
city Delhi
city Mumbai
city Kolkata
city Mumbai

Using ArrayList's remove() method with normal for loop

ArrayList's remove method can be used with normal for loop to remove an ArrayList in Java. If index is passed then it may give undesired result because of the fact that all the other elements are shifted to the left when an element is removed.
As example In the given program code if I want to remove the elements at index 3 & 4 then ideally Hyderabad and Bangalore should be removed from the list. Let's see what happens-

public class RemoveFromListDemo {
  public static void main(String[] args) {
    List<String> cityList = new ArrayList<String>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Kolkata");
    cityList.add("Hyderabad");
    cityList.add("Bangalore");
    cityList.add("Mumbai");
    
    for(int i = 0; i < cityList.size(); i++){
      if(i == 3 || i == 4){
        cityList.remove(i);
      }
    }
    
    System.out.println("After deletion " );
    for(String city : cityList){
      System.out.println("city " + city);
    }
  }
}

Output

After deletion 
city Delhi
city Mumbai
city Kolkata
city Bangalore

It can be seen that Hyderabad is removed alright but Mumbai is removed instead of Bangalore. This happened because after Hyderabad is removed elements in the list are shifted and Bangalore came in the place of Hyderabad and Mumbai in place of Bangalore. Thus Mumbai was at index 4 hence removed.

In the previous code if we were using city(object) in the if condition then it would have run fine.

public class RemoveFromListDemo {

  public static void main(String[] args) {
    List<String> cityList = new ArrayList<String>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Kolkata");
    cityList.add("Hyderabad");
    cityList.add("Bangalore");
    cityList.add("Mumbai");
    
    for(int i = 0; i < cityList.size(); i++){
      String city = cityList.get(i);
      if(city.equalsIgnoreCase("Kolkata") || city.equalsIgnoreCase("Bangalore")){
        cityList.remove(city);
      }
    }    
    System.out.println("After deletion " + cityList);
  }
}

Output

After deletion [Delhi, Mumbai, Hyderabad, Mumbai]

Using removeIf() to remove element from ArrayList

If you are using Java 8, then removeIf() method can be used to remove element from ArrayList, which takes Predicate functional interface as a parameter. In that case we can write the removal code with in one line as-

cityList.removeIf(p -> p.equalsIgnoreCase("Hyderabad") || 
    p.equalsIgnoreCase("Bangalore"));

ArrayList remove method and AutoBoxing problem

While removing elements from an ArrayList of Integers we may get problem because of Autoboxing. As already mentioned there are two overloaded remove methods-

  • Remove(int index)
  • Remove(Object o)

If we give an int as parameter then it will always be treated as a call to remove method with int parameter.
Let's clear it with an example

public class RemoveFromListDemo {
  public static void main(String[] args) {
    
    List<Integer> numberList = new ArrayList<Integer>();
    // adding to list as int, no need to do
    // new Integer(1)
    numberList.add(1);
    numberList.add(2);
    numberList.add(3);
    numberList.add(4);
    
    // Removing by index 1
    numberList.remove(1);
    // This time removing the integer Object 4
    numberList.remove(4);
  }
}

Output

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 3
 at java.util.ArrayList.rangeCheck(Unknown Source)
 at java.util.ArrayList.remove(Unknown Source)
 at org.netjs.prog.RemoveFromListDemo.main(RemoveFromListDemo.java:20)

So, even if a user thinks while removing the second time that he is giving an object as parameter and hoping autoboxing will take care of all the wrapping to Integer Object chore it won't happen in this case. Second call will also be treated as a call to remove method with int parameter. First remove has already removed one element so now the list size is 3 and trying to access index 4 in such a list will throw IndexOutOfBoundsException.

So in this case user has to explicitly tell the compiler that remove method which takes object as parameter has to be called.

numberList.remove(new Integer(4)); 

That's all for this topic How to Remove Elements From an ArrayList in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How ArrayList Works Internally in Java
  2. How to Remove Duplicate Elements From an ArrayList in Java
  3. How to Sort ArrayList in Java
  4. How to Join Lists in Java
  5. Java Collections Interview Questions And Answers

You may also like-

  1. equals() And hashCode() Methods in Java
  2. How HashSet Works Internally in Java
  3. ConcurrentHashMap in Java With Examples
  4. Interface Static Methods in Java 8
  5. Method reference in Java 8
  6. Functional Interfaces in Java
  7. Static Synchronization in Java Multi-Threading
  8. java.lang.ClassCastException - Resolving ClassCastException in Java

Friday, October 21, 2022

Java Map replace() With Examples

The replace() method in java.util.Map is added in Java 8. The replace() method replaces the value associated with the specified key only if the key is already mapped to some value. That's how replace() method differs from put() method, if a key is passed to the put() method that doesn't already exist in the Map then it will add the entry (key, value pair) to the Map.

Replace method in Java Map

There are two overloaded replace methods

1. V replace(K key, V value)

Replaces the entry for the specified key only if it is currently mapped to some value.

Paramters are-

  • key- The specified key for which value has to be replaced
  • value- New value to be associated with the specified key

Method returns the previous value if the key is mapped to a value. Returns null if key is not associated with any value, returns null if associated values is null for the key.

2. boolean replace(K key, V oldValue, V newValue)

Replaces the oldValue with newValue for the specified key only if the key is currently mapped to the oldValue.

  • key- Specified key for which value has to be changed
  • oldValue- Value expected to be associated with the specified key
  • newValue- Value that replaces the oldValue

Method returns true if the value was replaced, false otherwise.

replace() method Java examples

In this example we'll use replace(K key, V value) variant.

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

public class ReplaceDemo {
  public static void main(String[] args) {
    // Setting up a HashMap
    Map<String, String> cityMap = new HashMap<String, String>();
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Berlin");
    
    System.out.println("*** Map Initially ***");
    System.out.println(cityMap);
    String prevValue = cityMap.replace("3", "Chennai");
    System.out.println("Value that is replaced " + prevValue);
    
    prevValue = cityMap.replace("5", "Mumbai");
    System.out.println("Value that is replaced " + prevValue);
    
    System.out.println("*** Map After replacement ***");
    System.out.println(cityMap);
  }
}

Output

*** Map Initially ***
{1=New York City, 2=New Delhi, 3=Mumbai, 4=Berlin}
Value that is replaced Mumbai
Value that is replaced null
*** Map After replacement ***
{1=New York City, 2=New Delhi, 3=Chennai, 4=Berlin}

When "3" is passed as key in the replace() method the passed value replaces the previous value. In this case replace() method returns previous value associated with the key.

When "5" is passed as key there is no change in the Map as the key is not present in the HashMap. In this case replace() method returns null.

In this example we'll use replace(K key, V oldValue, V newValue) variant.

public class ReplaceDemo {

  public static void main(String[] args) {
    // Setting up a HashMap
    Map<String, String> cityMap = new HashMap<String, String>();
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Berlin");
    
    System.out.println("*** Map Initially ***");
    System.out.println(cityMap);
    boolean isReplaced = cityMap.replace("3", "Mumbai", "Chennai");
    System.out.println("Is value replaced " + isReplaced);
    
    isReplaced = cityMap.replace("4", "Mumbai", "Madrid");
    System.out.println("Is value replaced " + isReplaced);
    
    System.out.println("*** Map After replacement ***");
    System.out.println(cityMap);
  }
}

Output

*** Map Initially ***
{1=New York City, 2=New Delhi, 3=Mumbai, 4=Berlin}
Is value replaced true
Is value replaced false
*** Map After replacement ***
{1=New York City, 2=New Delhi, 3=Chennai, 4=Berlin}

First time value is replaced because key "3" was mapped with "Mumbai" initially. In this case replace() method returns true.

Second time there is no replacement because key "4" is there but it is not associated with "Mumbai". In this case replace() method returns false.

That's all for this topic Java Map replace() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to Remove Entry From HashMap in Java
  2. Java Map putIfAbsent() With Examples
  3. How HashMap Works Internally in Java
  4. HashSet Vs LinkedHashSet Vs TreeSet in Java
  5. Difference Between Comparable and Comparator in Java

You may also like-

  1. How to Convert Array to ArrayList in Java
  2. Java Phaser With Examples
  3. Java Abstract Class and Abstract Method
  4. java.lang.UnsupportedClassVersionError - Resolving UnsupportedClassVersionError in Java
  5. Convert double to int in Java
  6. Spring Setter Based Dependency Injection
  7. BeanFactoryAware Interface in Spring Framework
  8. FormGroup in Angular With Examples

Wednesday, October 19, 2022

How to Remove Entry From HashMap in Java

In this post we'll see how to remove an entry (key, value pair) from Map. Options you have are as given below-

  1. Using remove method- remove(Object key) provided by Map. See Example
  2. Using another remove method variant- remove(Object key, Object value) provided by Map. See Example
  3. Using remove() method provided by iterator. See Example
  4. Using removeIf() method. See Example

So, let's see when to use which method and why.

Removing entry from HashMap using remove(Object key) method

If you know the key for the entry which has to be removed, it is convenient to use remove(Object key) method rather than iterating the Map and then use iterator.remove() to remove the entry. This method returns the value which was associated with the removed key or null if the map contained no mapping for the key.

Here is an example with the map of cities where we'll try to remove Map.entry by passing one of the key.

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

public class RemoveEntryDemo {

  public static void main(String[] args) {
    // Setting up a HashMap
    Map<String, String> cityMap = new HashMap<String, String>();
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Berlin");
    
    System.out.println("*** Map Initially ***");
    System.out.println(cityMap);
      
    cityMap.remove("4");
    System.out.println("*** Map After removal ***");
    System.out.println(cityMap);
  }
}

Output

*** Map Initially ***
{1=New York City, 2=New Delhi, 3=Mumbai, 4=Berlin}
*** Map After removal ***
{1=New York City, 2=New Delhi, 3=Mumbai}

As you can see the entry with key as "4" is removed from the HashMap.

Removing entry from HashMap using remove(Object key, Object value) method

This is another overloaded remove() method in Map which makes removing an entry more restrictive. This method removes the entry for the specified key only if it is currently mapped to the specified value.

public class RemoveEntryDemo {

  public static void main(String[] args) {
    // Setting up a HashMap
    Map<String, String> cityMap = new HashMap<String, String>();
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Berlin");
    
    System.out.println("*** Map Initially ***");
    System.out.println(cityMap);
      
    cityMap.remove("4", "Berlin");
    System.out.println("*** Map After removal ***");
    System.out.println(cityMap);
  }
}

Output

{1=New York City, 2=New Delhi, 3=Mumbai, 4=Berlin}
*** Map After removal ***
{1=New York City, 2=New Delhi, 3=Mumbai}

Since the passed key "4" is mapped to the specified value "Berlin" so entry is removed.

If you give a value that is not mapped with any key no entry is removed. For example, if you try cityMap.remove("4", "London"); HashMap will have no change.

Using iterator's remove() method

If you don't know the key before hand and iterating the Map to find the entry that has to be removed then using remove() method of the Iterator is a safe bet.

If you have to iterate a HashMap then you need to get a collection view of the Map. The iterators returned by HashMap's "collection view methods" are fail-fast: if the Map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. Here is an example where remove() method of the Map is used to remove an entry (Structural modification) rather than using the remove() method of the iterator. This operation results in ConcurrentModificationException being thrown.

public class RemoveEntryDemo {

  public static void main(String[] args) {
    // Setting up a HashMap
    Map<String, String> cityMap = new HashMap<String, String>();
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Berlin");
    
    System.out.println("*** Map Initially ***");
    System.out.println(cityMap);
    Iterator<Entry<String, String>> itr = cityMap.entrySet().iterator();
    while(itr.hasNext()) {
      String key = itr.next().getKey();
      if(key.equals("2")) {
        cityMap.remove(key);
      }
    }

    System.out.println("*** Map After removal ***");
    System.out.println(cityMap);
  }
}

Output

*** Map Initially ***
{1=New York City, 2=New Delhi, 3=Mumbai, 4=Berlin}
Exception in thread "main" java.util.ConcurrentModificationException
	at java.base/java.util.HashMap$HashIterator.nextNode(HashMap.java:1597)
	at java.base/java.util.HashMap$EntryIterator.next(HashMap.java:1630)
	at java.base/java.util.HashMap$EntryIterator.next(HashMap.java:1628)
	at com.netjstech.collections.RemoveEntryDemo.main(RemoveEntryDemo.java:23)

Correct way to remove an entry from a Map while iterating it is to use iterator's remove() method.

public class RemoveEntryDemo {

  public static void main(String[] args) {
    // Setting up a HashMap
    Map<String, String> cityMap = new HashMap<String, String>();
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Berlin");
    
    System.out.println("*** Map Initially ***");
    System.out.println(cityMap);
    Iterator<Entry<String, String>> itr = cityMap.entrySet().iterator();
    while(itr.hasNext()) {
      if(itr.next().getKey().equals("2")) {
        itr.remove();
      }
    }

    System.out.println("*** Map After removal ***");
    System.out.println(cityMap);
  }
}

Output

*** Map Initially ***
{1=New York City, 2=New Delhi, 3=Mumbai, 4=Berlin}
*** Map After removal ***
{1=New York City, 3=Mumbai, 4=Berlin}

Using removeIf() method

removeIf() method is in Collection interface, since Map doesn't implement Collection so removeIf() method is not directly accessible in HashMap but after getting the Collection view of a Map removeIf() method can be used.

public class RemoveEntryDemo {

  public static void main(String[] args) {
    // Setting up a HashMap
    Map<String, String> cityMap = new HashMap<String, String>();
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Berlin");
    
    System.out.println("*** Map Initially ***");
    System.out.println(cityMap);
    cityMap.entrySet().removeIf(entry -> entry.getKey().equals("2"));


    System.out.println("*** Map After removal ***");
    System.out.println(cityMap);
  }
}

Output

*** Map Initially ***
{1=New York City, 2=New Delhi, 3=Mumbai, 4=Berlin}
*** Map After removal ***
{1=New York City, 3=Mumbai, 4=Berlin}
If you have a collection view of values then
cityMap.values().removeIf(v -> v.equals("Mumbai"));
Same way if you have a collection view of keys
cityMap.keySet().removeIf(k -> k.equals("2"));

That's all for this topic How to Remove Entry From HashMap in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Java Map putIfAbsent() With Examples
  2. Java Map containsValue() - Check if Value Exists in Map
  3. How to Sort a HashMap in Java
  4. How LinkedList Class Works Internally in Java
  5. How to Sort Elements in Different Order in TreeSet

You may also like-

  1. Difference Between HashMap And ConcurrentHashMap in Java
  2. CompletableFuture in Java With Examples
  3. super Keyword in Java With Examples
  4. strictfp in Java
  5. Angular Application Bootstrap Process
  6. ServiceLocatorFactoryBean in Spring
  7. Spring @Async @EnableAsync Annotations - Asynchronous Method Support
  8. Python Conditional Statement - if, elif, else Statements

Tuesday, October 18, 2022

Angular Pipes With Examples

Using Angular pipes you can transform data like strings, currency amounts, dates, many other values for display. You use pipe symbol (|) for Angular pipes and syntax is as follows.

value_expression | Angular pipe

For example there is a built-in Angular pipe named UpperCasePipe which is used to transform text to all upper case, let’s say there is a field ‘name’ which you want to display in uppercase then you’ll use this pipe as given below.

{{ name | uppercase}}

Monday, October 17, 2022

Java Map putIfAbsent() With Examples

The putIfAbsent() method in java.util.Map is added in Java 8 and it puts a new value for the specified key only if the specified key is not already associated with a value in the Map or is mapped to null. There is also a computeIfAbsent() method in Java which also puts a value if specified key is not already associated with a value but with computeIfAbsent() value is computed using the given mapping function.

Syntax of the putIfAbsent () method is as given below.

V putIfAbsent(K key, V value)

Parameters are as-

  • key- key with which the specified value is to be associated
  • value- value to be associated with the specified key

Method returns the previous value if the specified key is already associated with the value.

Returns null if specified key is not already present in the Map, which actually means key is absent and the method is inserting the given key, value pair in the Map. It may also mean that the key is present but associated with null value.

The default implementation for putIfAbsent() is as given below. As you can see just by using single method putIfAbsent() you get the logic of checking whether the key is already present or not in the map and putting the value in case key is not there (or associated value is null).

 V v = map.get(key);
 if (v == null)
     v = map.put(key, value);
 return v;

putIfAbsent () Java examples

1. In the first example we'll have a map of cities and we'll try to insert a new city with a key which already exists in the HashMap.

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

public class PutIfAbsentDemo {

  public static void main(String[] args) {
    // Setting up a HashMap
    Map<String, String> cityMap = new HashMap<String, String>();
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Berlin");
    String val = cityMap.putIfAbsent("4", "London");
    System.out.println("Value is- " + val);   
    System.out.println(cityMap);
  }
}

Output

Value is- Berlin
{1=New York City, 2=New Delhi, 3=Mumbai, 4=Berlin}

Since key already exists and mapped with a value in the HashMap so putIfAbsent() method won't replace the previous value with new value for the same key. Also notice the return value of the method which is the value associated with the specified key.

2. In this example we'll try to insert a new city with a key which is not already there in the Map.

public class PutIfAbsentDemo {

  public static void main(String[] args) {
    // Setting up a HashMap
    Map<String, String> cityMap = new HashMap<String, String>();
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Berlin");
    String val = cityMap.putIfAbsent("5", "London");
    System.out.println("Value is- " + val);   
    System.out.println(cityMap);
  }
}

Output

Value is- null
{1=New York City, 2=New Delhi, 3=Mumbai, 4=Berlin, 5=London}

Since key is not there in the Map so a new entry is added to the HashMap. Also notice the return value of the putifAbsent() method which is null this time because there was no mapping for the key.

3. In this example we'll take the scenario when the key exists in the HashMap but mapped with null.

public class PutIfAbsentDemo {

  public static void main(String[] args) {
    // Setting up a HashMap
    Map<String, String> cityMap = new HashMap<String, String>();
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", null);
    String val = cityMap.putIfAbsent("4", "London");
    System.out.println("Value is- " + val);   
    System.out.println(cityMap);
  }
}

Output

Value is- null
{1=New York City, 2=New Delhi, 3=Mumbai, 4=London}

Since the key is mapped to null so putIfAbsent() method associates the key with a new value.

That's all for this topic Java Map putIfAbsent() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Java Map merge() With Examples
  2. Java Map getOrDefault() Method With Examples
  3. Map.Entry Interface in Java
  4. EnumSet in Java With Examples
  5. Java Collections Interview Questions And Answers

You may also like-

  1. Java StampedLock With Examples
  2. CopyOnWriteArraySet in Java With Examples
  3. Garbage Collection in Java
  4. Difference Between Checked And Unchecked Exceptions in Java
  5. How to Read Excel File in Java Using Apache POI
  6. Spring Boot StandAlone (Console Based) Application Example
  7. Spring MVC Exception Handling - @ExceptionHandler And @ControllerAdvice Example
  8. Angular @HostBinding Decorator With Examples

Friday, October 14, 2022

Java Map merge() With Examples

In this post you'll learn about merge() method in java.util.map which is added in Java 8.

Syntax of the merge() method is as given below.

V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction)

merge() method works in the following way-

  1. If specified key is not present in the map or associated with null value then add the passed key and the value (second argument) to the Map.
  2. If specified key is already present in the Map then use the remapping function (third argument) to compute a new value for this key. That’s where this method derives its name from, if key is already there you have access to both old value and new value and using them you can compute an altogether new value which can then replace the value associated with the specified key.
  3. If the remapping function returns null then the mapping is removed from the Map.

This working of the merge() method can be explained as

V oldValue = map.get(key);
 V newValue = (oldValue == null) ? value : remappingFunction.apply(oldValue, value);
 if (newValue == null)
     map.remove(key);
 else
     map.put(key, newValue);

merge() method Java Example

1. In this example there is a HashMap having some items and their prices as key, value pairs. Using merge() we'll pass a key that is not present in the Map.

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

public class MergeDemo {

  public static void main(String[] args) {
    Map<String, Integer> itemMap = new HashMap<>();
    itemMap.put("Trousers", 1200);
    itemMap.put("Shirt", 800);
    itemMap.put("Shoes", 2000);
    System.out.println("*** Map Initially ***");
    System.out.println(itemMap);
    
    itemMap.merge("Belt", 750, (oldValue, newValue) -> newValue);
    System.out.println("*** Map After merge ***");
    System.out.println(itemMap);
  }
}

Output

{Shirt=800, Shoes=2000, Trousers=1200}
*** Map After merge ***
{Belt=750, Shirt=800, Shoes=2000, Trousers=1200}

Since key was not already present in the Map so 750 (second argument) is taken as value. Remapping function is not considered in this case.

2.In this example we'll use the same item map and specify a key that is already present in the Map. In the merge method there is a remapping function that increases the price by 20%. You can notice that the value computed using remapping function replaces the value associated with the key.

public class MergeDemo {

  public static void main(String[] args) {
    Map<String, Integer> itemMap = new HashMap<>();
    itemMap.put("Trousers", 1200);
    itemMap.put("Shirt", 800);
    itemMap.put("Shoes", 2000);
    itemMap.put("Belt", 750);
    System.out.println("*** Map Initially ***");
    System.out.println(itemMap);
    
    itemMap.merge("Belt", 750, 
      (oldValue, newValue) -> oldValue + (oldValue *20/100));
    System.out.println("*** Map After merge ***");
    System.out.println(itemMap);
  }
}

Output

{Shirt=800, Belt=750, Shoes=2000, Trousers=1200}
*** Map After merge ***
{Shirt=800, Belt=900, Shoes=2000, Trousers=1200}

3. In this example we'll take the scenario where remappingFunction of the merge() method returns null. In that case the (key, value) pair should be removed from the Map.

public class MergeDemo {

  public static void main(String[] args) {
    Map<String, Integer> itemMap = new HashMap<>();
    itemMap.put("Trousers", 1200);
    itemMap.put("Shirt", 800);
    itemMap.put("Shoes", 2000);
    itemMap.put("Belt", 750);
    System.out.println("*** Map Initially ***");
    System.out.println(itemMap);
    
    itemMap.merge("Belt", 750, 
      (oldValue, newValue) -> null);
    System.out.println("*** Map After merge ***");
    System.out.println(itemMap);
  }
}

Output

{Shirt=800, Belt=750, Shoes=2000, Trousers=1200}
*** Map After merge ***
{Shirt=800, Shoes=2000, Trousers=1200}

As you can see Map entry with key as "Belt" is removed from the Map as the remapping function returned null.

4. If you want to recompute all the values in the Map, merge() method is very convenient. Suppose in our item map we want to increase prices for all the items by 20%.

public class MergeDemo {

  public static void main(String[] args) {
    Map<String, Integer> itemMap = new HashMap<>();
    itemMap.put("Trousers", 1200);
    itemMap.put("Shirt", 800);
    itemMap.put("Shoes", 2000);
    itemMap.put("Belt", 750);
    System.out.println("*** Map Initially ***");
    System.out.println(itemMap);
    
    itemMap.forEach((k,v) -> itemMap.merge(k, v, 
          (oldValue, newValue)-> oldValue+ (oldValue * 20/100)));
    System.out.println("*** Map After merge ***");
    System.out.println(itemMap);
  }
}

Output

*** Map Initially ***
{Shirt=800, Belt=750, Shoes=2000, Trousers=1200}
*** Map After merge ***
{Shirt=960, Belt=900, Shoes=2400, Trousers=1440}

5. You can merge two HashMaps using merge() method too.

public class MergeDemo {

  public static void main(String[] args) {
    Map<String, Integer> itemMap1 = new HashMap<>();
    itemMap1.put("Trousers", 1200);
    itemMap1.put("Shirt", 800);
    itemMap1.put("Shoes", 2000);
    System.out.println("*** First Map ***");
    System.out.println(itemMap1);
    Map<String, Integer> itemMap2 = new HashMap<>();
    itemMap2.put("Shirt", 900);
    itemMap2.put("Belt", 750);
    System.out.println("*** Second Map ***");
    System.out.println(itemMap2);
    
    //Merging two Maps
    itemMap1.forEach((k,v) -> itemMap2.merge(k, v, 
          (oldValue, newValue)-> oldValue > newValue? oldValue : newValue));
    System.out.println("*** Map After merge ***");
    System.out.println(itemMap2);
  }
}

Output

*** First Map ***
{Shirt=800, Shoes=2000, Trousers=1200}
*** Second Map ***
{Shirt=900, Belt=750}
*** Map After merge ***
{Shirt=900, Belt=750, Shoes=2000, Trousers=1200}

Here merge method is used with Map itemMap2 so that will have the merged values. One of the key "Shirt" is present in both of the Maps so remapping function is used to compute the value (here logic is to take the highest value).

That's all for this topic Java Map merge() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Java Map getOrDefault() Method With Examples
  2. Java Map computeIfAbsent() With Examples
  3. equals() And hashCode() Methods in Java
  4. Difference Between HashMap And ConcurrentHashMap in Java
  5. How to Sort a HashMap in Java

You may also like-

  1. Java is a Strongly Typed Language
  2. static Block in Java
  3. Serialization and Deserialization in Java
  4. Java Program to Convert a File to Byte Array
  5. How to Use ngFor and ngIf on Same Element in Angular
  6. Spring util-namespace Example For Wiring Collection
  7. Spring Batch Processing With List of Objects in batchUpdate() Method
  8. Ternary Operator in Python

Thursday, October 13, 2022

Java Map getOrDefault() Method With Examples

The getOrDefault() method in java.util.Map is added in Java 8, this method gives you an option to return a default value if the specified key is not present in the Map. Value associated with the key is returned if the specified key is present in the Map.

Syntax of getOrDefault() method is as given below.

V getOrDefault(Object key, V defaultValue)

Parameters of the method are-

key- The key whose associated value is to be returned

defaultValue- The default value which has to be returned if the key is not present in the Map.

Method returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.

getOrDefault() method Java example

1. In this example we'll use getOrDefault() method to find value for the passed key, also pass a default value as a second argument which should be returned as value if the key is not found.

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

public class GetOrDefaultDemo {

  public static void main(String[] args) {
    // creating HashMap
      Map<String, String> langMap = new HashMap<String, String>();

      langMap.put("ENG", "English");
      langMap.put("NLD", "Dutch");
      langMap.put("BEN", "Bengali");
      langMap.put("ZHO", "Chinese");
      langMap.put("ZUL", "Zulu");
      
      String value = langMap.getOrDefault("HND", "Language not present");    
      System.out.println("Value for Key-HND: " + value);
      
      value = langMap.getOrDefault("ZUL", "Language not present");    
      System.out.println("Value for Key-ZUL: " + value);

  }
}

Output

Value for Key-HND: Language not present
Value for Key-ZUL: Zulu

Since key "HND" is not present in the HashMap so the default value is returned. Key "ZUL" is present in the HashMap so the value mapped to the key is returned.

2. getOrDefault() method also gives an option to write the program to Count Number of Times Each Character Appears in a String
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class CountCharacters {

  public static void main(String[] args) {
    CountCharacters cc = new CountCharacters();
    cc.countChars("I am a proud Indian");

  }
  // method used to count characters in a String
  public void countChars(String message){
    Map<Character, Integer> numCharMap = new HashMap<Character, Integer>();
    for(int i = 0; i < message.length(); i++){
      // Take one character 
      char c = message.charAt(i);
      // We don't need to count spaces
      if(c == ' ')
        continue;
      // If that character is already there in the map
      // then increase the value by 1, otherwise pass 0 //as default value
      numCharMap.put(c, numCharMap.getOrDefault(c, 0) + 1);
    }
    
    // Displaying the map values
    Set<Map.Entry<Character, Integer>> numSet = numCharMap.entrySet();
    for(Map.Entry<Character, Integer> m : numSet){
      System.out.println("Char- " + m.getKey() + " Count " + m.getValue());
    }
  }
}

Output

Char- p Count 1
Char- a Count 3
Char- r Count 1
Char- d Count 2
Char- u Count 1
Char- I Count 2
Char- i Count 1
Char- m Count 1
Char- n Count 2
Char- o Count 1

That's all for this topic Java Map getOrDefault() Method With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Java Map computeIfAbsent() With Examples
  2. Java Map merge() With Examples
  3. Java Map containsKey() - Check if Key Exists in Map
  4. How HashSet Works Internally in Java
  5. Java Collections Interview Questions And Answers

You may also like-

  1. How and Why to Synchronize ArrayList in Java
  2. Java Phaser With Examples
  3. static Keyword in Java With Examples
  4. Read or List All Files in a Folder in Java
  5. Binary Tree Traversal Using Depth First Search Java Program
  6. Check if String Present in Another String in Python
  7. Injector Hierarchy and Service Instances in Angular
  8. registerShutdownHook() Method in Spring Framework

Wednesday, October 12, 2022

Java Map containsValue() - Check if Value Exists in Map

If you want to check whether the specified value is present in the HashMap or not you can use containsValue() method in the java.util.Map which returns true if this map maps one or more keys to the specified value. Remember that in a Map key must be unique but one or more keys may have the same value.

Syntax of the method is as given below.

containsValue(Object value)

value- Passed parameter is the value whose presence in this map is to be tested.

Method returns true if this map maps one or more keys to the specified value. Returns false if there is no mapping for the specified value.

containsValue() Java example

1. Here we have a map with few key, value pairs. We want to check if the specified value is already there or not using containsValue() method.

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

public class ContainsValueDemo {

  public static void main(String[] args) {
    // creating HashMap
      Map<String, String> langMap = new HashMap<String, String>();

      langMap.put("ENG", "English");
      langMap.put("NLD", "Dutch");
      langMap.put("ZHO", "Chinese");
      langMap.put("BEN", "Bengali");
      langMap.put("ZUL", "Zulu");
      boolean isExistingMapping = langMap.containsValue("Dutch");
      System.out.println("Dutch is there in the Map-- " + isExistingMapping);
      isExistingMapping = langMap.containsValue("Tamil");
      System.out.println("Tamil is there in the Map-- " + isExistingMapping);
  }
}

Output

Dutch is there in the Map-- true
Tamil is there in the Map-false

2. You can also use containsValue() method to add a new entry to the Map after checking that the value is already not there.

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

public class ContainsValueDemo {

  public static void main(String[] args) {
    // creating HashMap
      Map<String, String> langMap = new HashMap<String, String>();

      langMap.put("ENG", "English");
      langMap.put("NLD", "Dutch");
      langMap.put("ZHO", "Chinese");
      langMap.put("BEN", "Bengali");
      langMap.put("ZUL", "Zulu");
      
      if(!langMap.containsValue("Tamil")) {
        langMap.put("TAM", "Tamil");
      }else {
        System.out.println("Value already there in the Map");
      }            
      System.out.println("Language Map-- " + langMap);
  }
}

Output

Language Map-- {ZHO=Chinese, ZUL=Zulu, TAM=Tamil, NLD=Dutch, BEN=Bengali, ENG=English}

That's all for this topic Java Map containsValue() - Check if Value Exists in Map. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Java Map containsKey() - Check if Key Exists in Map
  2. Java Map computeIfAbsent() With Examples
  3. How HashMap Works Internally in Java
  4. HashMap Vs LinkedHashMap Vs TreeMap in Java
  5. Java Collections Interview Questions And Answers

You may also like-

  1. ConcurrentLinkedDeque in Java With Examples
  2. Difference Between Comparable and Comparator in Java
  3. Association, Aggregation And Composition in Java
  4. Constructor Chaining in Java
  5. Find Largest And Smallest Number in a Given Array Java Program
  6. Pure and Impure Pipes in Angular
  7. Python Exception Handling - try,except,finally
  8. Spring Component Scan to Automatically Discover Beans

Tuesday, October 11, 2022

Generics in Java

There have been many new feature additions in Java over the year, with introduction of lambda expressions in Java 8 it has even moved toward functional programming. But long before the lambda expressions and stream API there was one change which had a very big impact on the way you program and that was generics which was added in Java 5.

Generics in Java not only added a new way to declare classes, methods or interface but it also changed many of the classes in the API, Java collections API is an example. Initially it took some time getting used to the parameters like T, K or V with the classes or methods but now its quite a familiar thing and very much a part of your daily programming.

Java Generics

Generics in Java enable you to specify type parameters when defining classes, interfaces and methods. Here type parameter is the type of data (class or interface) which these classes, interfaces and methods will operate upon.

As example, when you say List<T> that means a list which will store elements of type T. Since you have specified a type parameter so this List class is generic and T is the type parameter which specifies the type of element stored in the List.

Generic class format in Java

A generic class is defined using the following format:

class name<T1, T2, ..., Tn> { 
  /* ... */ 
}

The type parameter section, delimited by angle brackets (<>), follows the class name. It specifies the type parameters (also called type variables) T1, T2, ..., and Tn.

Java Generics - Type Parameter Naming Conventions

By convention, generic type parameter names are single, upper case letters. That helps n distinguishing between type parameters and normal variables.

The most commonly used type parameter names are:

  • E - Element (used extensively by the Java Collections Framework)
  • K - Key
  • N - Number
  • T - Type
  • V - Value
  • S,U,V etc. - 2nd, 3rd, 4th types

Benefits of Generics in Java

You might be thinking there is already an Object class which provides almost the same thing, as Object is super class of all the other classes so Object class can be used to make a class generic. Though that can be done but it may cause some unseen problems because there is no type safety.

Let’s say you have a List where you intend to store strings and you have not made it generic that means all its elements will be stored as objects of type Object-

List strList = new ArrayList();
strList.add("a");
strList.add("b");
strList.add(new Integer(4));
Iterator itr = strList.iterator();
while(itr.hasNext()){
 String str = (String)itr.next();
 System.out.println("" + str);
}

Since elements are stored as class Object type so there won’t be any compile time error if you store an integer too (as done in this line strList.add(new Integer(4));), even if you intended to store Strings.

Since the elements are stored as class Object type so you need to cast those elements to String while retrieving. At that time you will get a run time exception when the code will try to cast Integer to String.

So the code snippet shown above will throw run time exception-
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

That brings to the fore couple of benefits of using generics in Java-

  • Stronger type checks at compile time- In the above code if you use generics and specify the parameterized type of List as String you will get compile time error if an attempt is made to add element of any other type to the list. A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.

    As example-

    List<String> strList = new ArrayList<String>();
    strList.add("a");
    strList.add("b");
    strList.add(new Integer(4));
    

    With generics this code will throw following compile-time error if you try to add Integer to the list
    The method add(String) in the type List<String> is not applicable for the arguments (Integer)

  • Casting is not required- Another benefit you get with generics in Java is that cast is not required. Since you already specify the type with generics so explicit cast is not required.

    As example-

    List<String> strList = new ArrayList<String>();
    strList.add("a");
    strList.add("b");
    strList.add("c");
    
    Iterator<String> itr = strList.iterator();
    while(itr.hasNext()){
      String str = itr.next();
      System.out.println("" + str);
    }
    

    Here you see casting is not required when retrieving elements from the list.

  • Enabling programmers to implement generic algorithms– In many algorithms, logic remains same, irrespective of the data they are used with. On the other hand, generics make it possible to write classes, methods and interface that work with different kind of data that too in a type safe manner. Now combine these two facts and the result you can write generic algorithms that work with any type of data.

    Let’s take a simple example to see how to create a generic class with parameterized type. While creating an object of the class you can specify the type, which in generics terminology is called generic type invocation, which replaces T with some concrete value.

    Generic class

    public class GenType<T> {
      T obj;
    
      public T getObj() {
        return obj;
      }
    
      public void setObj(T obj) {
        this.obj = obj;
      } 
    }
    

    Using Generic class

    public class GenericDemo {
      public static void main(String[] args) {
        // With Integer type
        GenType<Integer> genInt = new GenType<Integer>();
        genInt.setObj(21);
        int value = genInt.getObj();
        System.out.println("integer value " + value);
        
        // With String type
        GenType<String> genStr = new GenType<String>();
        genStr.setObj("Generic class test");
        String str = genStr.getObj();
        System.out.println("String value " + str);
        
        // With Double type
        GenType<Double> genDouble = new GenType<Double>();
        genDouble.setObj(34.56);
        double dblValue = genDouble.getObj();
        System.out.println("Double value " + dblValue);
      }
    }
    

    Output

    integer value 21
    String value Generic class test
    Double value 34.56
    

    Here you see that the same generic class is first invoked with Integer type, then String and then Double. And you get the added benefit of type safety and no chance of run time exception (which is a probability if you had used an Object class to make the class generic).

Points to remember

  1. Generics in Java provide type safety as there are stronger type checks at compile-time.
  2. Generics don’t work with primitive types, type arguments passed to the type parameters must be references.
  3. You can have generic classes, generic methods and generic interfaces.
  4. Type parameters are erased when generic classes are compiled.
  5. A generic class with type parameters can’t have static members using the type parameter. As example -
    public class GenType<T> {
      static T obj;
      .....
      .....
    }
    
    This code will have compile-time error - Cannot make a static reference to the non-static type T.
  6. In Java 7 and later you can replace the type arguments required to invoke the constructor of a generic class with an empty set of type arguments (<>) as long as the compiler can determine, or infer, the type arguments from the context. This pair of angle brackets, <>, is informally called the diamond.
    As example- List<Integer> ls = new ArrayList<>();

    You don’t need to write <Integer> again, empty set of type argument (<>) will do, type will be inferred automatically.

That's all for this topic Generics in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Generic Class, Interface And Generic Method in Java
  2. Bounded Type Parameter in Java Generics
  3. Wildcard in Java Generics
  4. Type Erasure in Java Generics
  5. Covariant Return Type in Java

You may also like-

  1. Interface Default Methods in Java
  2. Effectively Final in Java 8
  3. Method Reference in Java
  4. Java ThreadLocal Class With Examples
  5. Is String Thread Safe in Java
  6. Dependency Injection using factory-method in Spring
  7. strictfp in Java
  8. Polymorphism in Java

Monday, October 10, 2022

Java Map containsKey() - Check if Key Exists in Map

If you want to check whether the specified key is present in the HashMap or not you can use containsKey() method in the java.util.Map which returns true only if Map contains a mapping for the specified key.

Syntax of the method is as given below.

containsKey(Object key)

key- key whose presence in this map is to be tested

Method returns true if this map contains a mapping for the specified key otherwise returns false.

containsKey() Java example

1. Here we have a map of items with item and its price as key, value pairs. If you want to check if the specified key is already there or not.

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

public class ContainsKeyDemo {

  public static void main(String[] args) {
    Map<String, Integer> itemMap = new HashMap<>();
    itemMap.put("Trousers", 1200);
    itemMap.put("Shirt", 800);
    itemMap.put("Shoes", 2400);
    itemMap.put("Belt", 750);
    
    if(itemMap.containsKey("Shoes")) {
      System.out.println("Item already present in the Map");
    }
  }
}

Output

Item already present in the Map

2. You can also use containsKey() method to add a new entry to the Map after checking that the key is already not there.

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

public class ContainsKeyDemo {

  public static void main(String[] args) {
    Map<String, Integer> itemMap = new HashMap<>();
    itemMap.put("Trousers", 1200);
    itemMap.put("Shirt", 800);
    itemMap.put("Belt", 750);  
    
    boolean isItemShoeExist = itemMap.containsKey("Shoes");
    System.out.println("Does key Shoes exist in the HashMap- " + isItemShoeExist);
    
    if(!itemMap.containsKey("Shoes")) {
      itemMap.put("Shoes", 2400);      
    }else {
      System.out.println("Item already present in the Map");
    }
    System.out.println("Map Values- " + itemMap);
  }
}

Output

Does key Shoes exist in the HashMap- false
Map Values- {Shirt=800, Belt=750, Shoes=2400, Trousers=1200}

As you can see when checking for the key which is not present in the Map, containsKey method returns false. Using that you can add a new entry to the HashMap.

That's all for this topic Java Map containsKey() - Check if Key Exists in Map. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Java Map containsValue() - Check if Value Exists in Map
  2. Java Map computeIfAbsent() With Examples
  3. TreeMap in Java With Examples
  4. Unmodifiable or Immutable Map in Java
  5. Java Collections Interview Questions And Answers

You may also like-

  1. How to Convert ArrayList to Array in Java
  2. isAlive() And join() Methods in Java Multi-Threading
  3. finally Block in Java Exception Handling
  4. Comparing Enum to String in Java
  5. Angular ngIf Directive With Examples
  6. Setting Wild Card Route in Angular
  7. Spring Boot REST API CRUD Example With Spring Data JPA
  8. Spring Object XML Mapping (OXM) JAXB Example

Tuesday, October 4, 2022

Java Map computeIfAbsent() With Examples

The computeIfAbsent() method in java.util.Map is added in Java 8 and it computes a new value for the specified key only if that key is not already present in the Map or it is present but associated with a null value.

Syntax of the computeIfAbsent() method is as given below.

computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)

Parameters are as-

  • key- First parameter is the key with which the value is to be associated.
  • remappingFunction- This parameter is of type Function functional interface and provides a function to compute a value.

Method returns the new value associated with the specified key if the old value was null otherwise return the old value itself. Returns null in case computed new value is null.

Logic for this method is somewhat similar to as given below.

if (map.get(key) == null) {
     V newValue = mappingFunction.apply(key);
     if (newValue != null)
         map.put(key, newValue);
 }
  1. If value for the specified key is null and the computed new value is not null then add this entry to the Map.
  2. If value for the specified key is null and the computed new value is also null then do nothing (Map remains unchanged).
  3. If old value for the specified key is not null (key already present) then also Map remains unchanged.

computeIfAbsent() Java examples

1. Here we have a map of items with item and its price as key, value pairs. We'll try to add a new entry to the Map by checking if that key is already not present.

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

public class ComputeAbsentDemo {

  public static void main(String[] args) {
    Map<String, Integer> itemMap = new HashMap<>();
    itemMap.put("Trousers", 1200);
    itemMap.put("Shirt", 800);
    itemMap.put("Shoes", 2000);
    
    System.out.println("*** Map Initially ***");
    System.out.println(itemMap);
    // adding new entry
    itemMap.computeIfAbsent("Belt", (k) -> 750);
    System.out.println("*** Map After compute ***");
    System.out.println(itemMap);
  }
}

Output

*** Map Initially ***
{Shirt=800, Shoes=2000, Trousers=1200}
*** Map After compute ***
{Belt=750, Shirt=800, Shoes=2000, Trousers=1200}

As you can see a new key, value pair Belt=750 is added to the HashMap.

2. If key is already there but the value is null then value is modified if new value is not null.

public class ComputeAbsentDemo {

  public static void main(String[] args) {
    Map<String, Integer> itemMap = new HashMap<>();
    itemMap.put("Trousers", 1200);
    itemMap.put("Shirt", 800);
    itemMap.put("Shoes", 2000);
    itemMap.put("Belt", null);
    
    System.out.println("*** Map Initially ***");
    System.out.println(itemMap);
    // modify value for key with null value
    itemMap.computeIfAbsent("Belt", (k) -> 750);
    System.out.println("*** Map After compute ***");
    System.out.println(itemMap);
  }
}

Output

*** Map Initially ***
{Shirt=800, Belt=null, Shoes=2000, Trousers=1200}
*** Map After compute ***
{Shirt=800, Belt=750, Shoes=2000, Trousers=1200}

3. If non-null value is already present for the specified key then the map remains unchanged.

public class ComputeAbsentDemo {

  public static void main(String[] args) {
    Map<String, Integer> itemMap = new HashMap<>();
    itemMap.put("Trousers", 1200);
    itemMap.put("Shirt", 800);
    itemMap.put("Shoes", 2000);
    itemMap.put("Belt", 750);
    
    System.out.println("*** Map Initially ***");
    System.out.println(itemMap);
      
    itemMap.computeIfAbsent("Belt", (k) -> 850);
    System.out.println("*** Map After compute ***");
    System.out.println(itemMap);
  }
}

Output

*** Map Initially ***
{Shirt=800, Belt=750, Shoes=2000, Trousers=1200}
*** Map After compute ***
{Shirt=800, Belt=750, Shoes=2000, Trousers=1200}

Since key "Belt" is already there in the HashMap with an associated non-null value, Map remains unchanged (Value for key "Belt" doesn't change to 850).

That's all for this topic Java Map computeIfAbsent() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Java Map computeIfPresent() With Examples
  2. Java Map putIfAbsent() With Examples
  3. ConcurrentSkipListMap in Java With Examples
  4. Fail-Fast Vs Fail-Safe Iterator in Java
  5. Java DelayQueue With Examples

You may also like-

  1. Generics in Java
  2. How HashSet Works Internally in Java
  3. Why Java String is Immutable
  4. BigInteger in Java With Examples
  5. Java Program to Delete a Node From Binary Search Tree (BST)
  6. Pure and Impure Pipes in Angular
  7. Spring Email Scheduling Example Using Quartz Scheduler
  8. Spring JdbcTemplate Insert, Update And Delete Example