Sunday 13 May 2018

Lambda Expression that accept two objects

Create a Functional interface that accepts two objects. Object can be of same type (or) of different type.

BiObjectConsumer.java
package com.sample.functional.interfaces;

/**
 * Functional interface that accepts two objects. Object can be of same type
 * (or) of different type.
 * 
 * @author Krishna
 *
 * @param <T1>
 *            First object type
 * @param <T2>
 *            Second Object type
 */
public interface BiObjectConsumer<T1, T2> {

 public void operation(T1 obj1, T2 obj2);
}

Application.java
package com.sample.app;

import java.util.*;

import com.sample.functional.interfaces.BiObjectConsumer;

public class Application {

 private static void performOperationOnMap(BiObjectConsumer<Map<String, String>, String> biObjectConsumer,
   Map<String, String> map, String value) {
  biObjectConsumer.operation(map, value);
 }

 private static void printMap(Map<String, String> map) {
  System.out.println("Elements in the map are");
  Set<String> set = map.keySet();
  for (String key : set) {
   System.out.println(key + " : " + map.get(key));
  }
  System.out.println("\n");
 }

 public static void main(String args[]) throws Exception {
  Map<String, String> countries = new HashMap<>();
  countries.put("Bhutan", "Thimpu");
  countries.put("Canada", "Ottawa");
  countries.put("Cuba", "Havana");
  countries.put("Romania", "Bucharest");
  countries.put("Zimbabwe", "Harare");

  printMap(countries);

  /* Search for an element in the map */
  performOperationOnMap((map, data) -> {
   if (map.containsKey(data)) {
    String result = String.format("Map contains the key \"%s\"\n", data);
    System.out.println(result);
    return;
   }

   String result = String.format("Map do not the key \"%s\"\n", data);
   System.out.println(result);

  }, countries, "Romania");

  /* Remove an element */
  performOperationOnMap((map, data) -> {
   String result = String.format("Removing the key \"%s\"\n", data);
   System.out.println(result);
   map.remove(data);
  }, countries, "Cuba");

  printMap(countries);

 }
}


Output
Elements in the map are
Canada : Ottawa
Cuba : Havana
Bhutan : Thimpu
Romania : Bucharest
Zimbabwe : Harare


Map contains the key "Romania"

Removing the key "Cuba"

Elements in the map are
Canada : Ottawa
Bhutan : Thimpu
Romania : Bucharest
Zimbabwe : Harare






Previous                                                 Next                                                 Home

No comments:

Post a Comment