Tuesday, May 12, 2026

Agents in LangChain With Examples

In the post Tool Calling in LangChain we saw how to execute the created tools manually by parsing the tool call sent by LLM and then explicitly invoking the required function. While effective for simple workflows, this manual orchestration quickly becomes hard to follow, when tasks demand multiple steps, dynamic reasoning and adaptive decision making.

This is where agents in LangChain change the way tools are executed. Agents automate tool calling by using a Large Language Model (LLM) as a reasoning engine. Instead of manually deciding which tool to call and when, agents use a loop to iteratively reason about a task, select necessary tools and invoke them automatically, and observe outcomes until the task is complete.

Agents in LangChain: Smarter Task Automation

At their core, agents combine four essential components:

  • LLM (The Brain): Provides reasoning and decision logic.
  • Tools: External functions, APIs, or data sources that are to be called automatically by agents.
  • Memory: Maintains context across multiple turns for continuity.
  • Agent Runtime (LangGraph): A graph-based agent runtime using LangGraph is created that defines how your agent processes information.

create_agent function in LangChain

In earlier versions of LangChain, developers had to choose between multiple specialized agent constructors such as create_react_agent, create_openai_functions_agent, and others. Each of these was tailored to a specific agent type or execution style, but this fragmented the developer experience and made maintenance harder.

Over time, the LangChain team consolidated these patterns. All the older agent creation functions were deprecated, and the unified create_agent function was introduced which builds a graph based agent runtime powered by LangGraph.

  • A graph is made up of nodes (steps) and edges (connections) that defines how your agent processes information.
  • Nodes represent actions such as calling the model, executing tools, or running middleware.
  • Edges define how the agent moves between these steps.

create_agent function syntax

create_agent(
  model,  
  tools,
  system_prompt,
  middleware,
  response_format,
  ...
)

Parameters:

  1. model
    • The LLM you want the agent to use (e.g., OpenAI, Anthropic, Gemini).
    • This is the reasoning engine that interprets input, decides actions, and generates responses.
  2. tools
    • A list of external functions or APIs the agent can call (e.g., calculator, search, database query).
  3. system_prompt
    • An optional system prompt for the LLM that sets the agent's role, tone, and behavior.
    • Example: "You are a helpful assistant that uses tools when needed."
  4. middleware
    • Optional components that intercept or modify the agent's behaviour at various stages.
    • Can be used for logging, monitoring, or injecting custom logic before/after tool calls.
  5. response_format
    • Defines how the agent should structure its final output.
    • Can be a ToolStrategy, ProviderStrategy, or a Pydantic model class.

Apart from these parameters there are other optional parameters to persist the state of graph (checkpoint), persisting data (store) and many more.

How Agent Loop Works with create_agent

Agents in LangChain
  1. Agent Node Calls the Model
    • The agent starts by sending the messages list to the language model.
    • The system prompt is applied first to guide the model's behavior.
  2. Model Produces a Response
    • The model returns an AIMessage.
    • If this AIMessage contains tool_calls, it means the model wants to use a tool.
  3. Tools Node Executes the Tools
    • The agent passes the tool calls to the Tools node.
    • Each tool is executed with the provided arguments.
    • The results are wrapped as ToolMessage objects and added back to the messages list.
  4. Agent Node Calls the Model Again
    • With the updated messages list (including tool results), the agent re invokes the model.
    • This allows the model to reason over the new information.
  5. Loop Continues
    • Repeat steps 2–4
    • The process repeats until no more tool_calls are present in the response.

LangChain Example - Agent with Web Search + Math Tools

Imagine you want an agent that can handle questions requiring both real time data and calculations. For example: "What is the commission on 15 grams of gold at 5% commission rate?"

This workflow requires two tasks-

  1. Fetching the current rate of gold per gram and then calculating cost price of given quantity.
  2. Apply the commission rate to compute the commission amount on that cost price.

So, we can define two tools for these 2 tasks:

  1. Web search tool- Searches the current market rate of gold per gram.
  2. Commission Calculator Tool- takes the cost price and commission rate, then returns the commission value.

The agent orchestrates these tools in sequence; first retrieving the gold price, then performing the commission calculation, and finally returning the complete answer to the user. Important thing here is as a developer you don’t need to call any of the tools manually it will be handled by agent run-time.

Note that the code uses OpenRouter as inference provider which needs registering with the OpenRouter and getting the API key (in case you are going to use the same setup). That API key needs to be stored in .env file with the key as "OPENROUTER_API_KEY". Needs installation of langchain-openrouter and pytz packages too.

from langchain_community.tools import DuckDuckGoSearchRun
from langchain_core.tools import tool
from langchain_openrouter import ChatOpenRouter
from langchain.agents.structured_output import ToolStrategy
from datetime import datetime
import pytz
from langchain.agents import create_agent
from dotenv import load_dotenv
load_dotenv()  # Load environment variables from .env file
from langchain_core.output_parsers import PydanticOutputParser
from pydantic import BaseModel, Field

# Pydantic model for structured output
class GoldCommissionResult(BaseModel):
    gold_price_per_gram: float = Field(..., description="Today's 24K gold price per gram in INR (Mumbai, IST)")
    grams: int = Field(..., description="Number of grams requested")
    cost_price: float = Field(..., description="Total cost price in INR for the requested grams")
    commission_rate: float = Field(..., description="Commission rate applied (decimal, e.g., 0.05 for 5%)")
    commission_value: float = Field(..., description="Final commission value in INR")

@tool
def search_web_tool(query: str):
    '''Tool function to search the web for the given query using DuckDuckGo search results.'''
    print(f"Searching the web for: {query}")
    search_tool = DuckDuckGoSearchRun(num_results=3)
    results = search_tool.run(query)
    return results

@tool
def calculate_commission(cost_price: float, commission_rate: float) -> float:
    '''Tool function to evaluate commission on the cost price.'''
    print(f"Calculating commission for cost price: {cost_price} and commission rate: {commission_rate}")
    return cost_price * commission_rate

model = ChatOpenRouter(model="openai/gpt-oss-120b", temperature=0.1)

system_prompt = """
You are a helpful assistant working in Mumbai, India.
All tool calls, time-sensitive tasks and responses must adhere to IST.
When asked about gold price and commission:
1. Use search_web_tool to fetch today's 24K gold price in Mumbai (per gram, INR).
2. Multiply by the grams requested to get cost price.
3. Pass that cost price into calculate_commission with the given commission rate.
"""

# Create agent with tools
agent = create_agent(model,
    tools=[search_web_tool, calculate_commission],
    system_prompt=system_prompt,
    response_format=ToolStrategy(GoldCommissionResult)
)

# This function gets today's date in IST timezone, which is crucial for accurate web search results related to gold prices in India.
def get_today_date_ist():
    ist = pytz.timezone("Asia/Kolkata")
    return datetime.now(ist).strftime("%Y-%m-%d")

today = get_today_date_ist()

result = agent.invoke({"messages": [{"role": "user", "content": f"What is the commission on 15 gram of gold on {today} price for 24K in INR at 5% commission rate?"}]})

print(result)
#final answer is in structured_response field of the result, which is an instance of GoldCommissionResult
print("Answer:",result["structured_response"])

Output

Searching the web for: 24K gold price per gram Mumbai today
Calculating commission for cost price: 243225.0 and commission rate: 0.05
{'messages': [HumanMessage(content='What is the commission on 15 gram of gold on 2026-05-11 price for 24K in INR at 5% commission 
rate?', additional_kwargs={}, response_metadata={}, id='560afba8-0100-4d00-9bc5-2ee91ec8404a'), AIMessage(content='', 
additional_kwargs={'reasoning_content': 'We need to get today\'s 24K gold price in Mumbai per gram, but the user asks for price on 2026-05-11. That\'s a future date. We cannot fetch future price. Probably we interpret "today\'s price" as of now (IST). The user asks "on 2026-05-11 price". That date is in future, we cannot get. We could respond that we can only fetch current price. But the instruction says: When asked about gold price and commission: Use search_web_tool to fetch today\'s 24K gold price in Mumbai (per gram, INR). So we should fetch current price. Then compute for 15 grams, commission 5%.\n\nThus steps: search web for "24K gold price per gram Mumbai today". Then calculate cost = price * 15. Then calculate commission with rate 0.05.\n\nLet\'s do search.', 'reasoning_details': [{'type': 'reasoning.text', 'format': 'unknown', 'index': 0, 'text': 'We need to get today\'s 24K gold price in Mumbai per gram, but the user asks for price on 2026-05-11. That\'s a future date. We cannot fetch future price. Probably we interpret "today\'s price" as of now (IST). The user asks "on 2026-05-11 price". That date is in future, we cannot get. We could respond that we can only fetch current price. But the instruction says: When asked about gold price and commission: Use search_web_tool to fetch today\'s 24K gold price in Mumbai (per gram, INR). So we should fetch current price. Then compute for 15 grams, commission 5%.\n\nThus steps: search web for "24K gold price per gram Mumbai today". Then calculate cost = price * 15. Then calculate commission with rate 0.05.\n\nLet\'s do search.'}]}, response_metadata={'model_name': 'openai/gpt-oss-120b', 'id': 'gen-1778481749-VEyzaZUsFowGl8YVTxNr', 'created': 1778481749, 'object': 'chat.completion', 'finish_reason': 'tool_calls', 'logprobs': None, 'model_provider': 'openrouter'}, id='lc_run--019e15c5-db77-7482-8235-aa43535013e1-0', 
tool_calls=[{'name': 'search_web_tool', 'args': {'query': '24K gold price per gram Mumbai today'}, 'id': 'chatcmpl-tool-038985043b0542f19f4f98bb50691877', 'type': 'tool_call'}], invalid_tool_calls=[], usage_metadata={'input_tokens': 362, 'output_tokens': 215, 'total_tokens': 577, 'input_token_details': {'cache_read': 0, 'cache_creation': 0}, 'output_token_details': {'reasoning': 185}}), 
ToolMessage(content="Checktoday's livegoldrate inMumbaifor 22K and24Kgoldpergram. Get real-timepriceupdates, compare daily rates, and track 10-day historicalgoldpricetrends across major Indian cities on Upstox. 24KGoldRate.Today,goldremains deeply rooted in the culture ofMumbai. From the iconicgold'taalis' (mangalsutras) exchanged during Maharashtrian weddings to the delicategold'nath' (nose rings) adorning women during festivals,goldsignifies prosperity, blessings, and the... GoldPriceTodayinMumbaiis 16,215 Indian Rupee (INR)/gram24K. This is equal to 625.17 (AED) and 170.22 (USD).Goldpricein India is calculated bothperounce,gram, kilogram and tola and for the most common karats. Today'sgoldpricein India stands at ?15,234pergramfor 24 karatgold(99.9% purity), ?13,964pergramfor 22 karatgold(91.6% purity), and ?11,425pergramfor 18 karatgold(75% purity).Goldhas over the years been a perfect hedge against inflation. Investors are increasingly looking... Today24K, 22K & 18K CaratGoldPricePerGramin India (INR).This tools helps you project your potentialgoldrate aspertodaysgoldrate.", name='search_web_tool', id='b9f343d2-4312-4ee1-ab03-7afb687fba02', tool_call_id='chatcmpl-tool-038985043b0542f19f4f98bb50691877'), AIMessage(content='', additional_kwargs={'reasoning_content': 'The user asks: "What is the commission on 15 gram of gold on 2026-05-11 price for 24K in INR at 5% commission rate?" We need today\'s price? Actually date is 2026-05-11, which is future. We cannot fetch future price. Probably they meant today\'s price (current date). We have fetched a price: 16,215 INR per gram (source says). Need to compute cost price = 15 * 16215 = 243,225 INR. 
Then commission = 5% of that = 0.05 * 243,225 = 12,161.25 INR.\n\nWe need to call calculate_commission with cost_price and commission_rate. Then output result with details. Let\'s call calculate_commission.', 'reasoning_details': [{'type': 'reasoning.text', 'format': 'unknown', 'index': 0, 'text': 'The user asks: "What is the commission on 15 gram of gold on 2026-05-11 price for 24K in INR at 5% commission rate?" We need today\'s price? Actually date is 2026-05-11, which is future. We cannot fetch future price. Probably they meant today\'s price (current date). We have fetched a price: 16,215 INR per gram (source says). Need to compute cost price = 15 * 16215 = 243,225 INR. Then commission = 5% of that = 0.05 * 243,225 = 12,161.25 INR.\n\nWe need to call calculate_commission with cost_price and commission_rate. Then output result with details. Let\'s call calculate_commission.'}]}, response_metadata={'model_name': 'openai/gpt-oss-120b', 'id': 'gen-1778481758-mex8jK3ZFTGVBLri5Qps', 'created': 1778481758, 'object': 'chat.completion', 'finish_reason': 'tool_calls', 'logprobs': None, 'model_provider': 'openrouter'}, id='lc_run--019e15c6-01d5-7f82-8647-cb759f32def0-0', tool_calls=[{'name': 'calculate_commission', 'args': {'cost_price': 243225, 'commission_rate': 0.05}, 'id': 'chatcmpl-tool-b3af5980739b4d6e936aba6193b19634', 'type': 'tool_call'}], invalid_tool_calls=[], usage_metadata={'input_tokens': 703, 'output_tokens': 201, 'total_tokens': 904, 'input_token_details': {'cache_read': 0, 'cache_creation': 0}, 'output_token_details': {'reasoning': 148}}), 
ToolMessage(content='12161.25', name='calculate_commission', id='31475b2e-6486-40bd-98f9-681e5d1b5409', tool_call_id='chatcmpl-tool-b3af5980739b4d6e936aba6193b19634'), AIMessage(content='', additional_kwargs={'reasoning_content': 'We need to produce final answer with details: gold price per gram, cost price for 15g, commission value. The search result gave two different numbers: 16,215 INR per gram and 15,234 INR per gram. Need to pick correct today\'s 24K gold price in Mumbai. 
The snippet includes both. Which is correct? Probably the first line "GoldPriceTodayinMumbaiis 16,215 Indian Rupee (INR)/gram24K." 
We'll use 16,215. Multiply 16,215 * 15 = 243,225 INR cost price. Commission 5% = 12,161.25 INR.\n\nWe should also provide a 
structured result using GoldCommissionResult. Let\'s call the function to output structured result.', 'reasoning_details': 
[{'type': 'reasoning.text', 'format': 'unknown', 'index': 0, 'text': 'We need to produce final answer with details: gold price 
per gram, cost price for 15g, commission value. The search result gave two different numbers: 16,215 INR per gram and 15,234 
INR per gram. Need to pick correct today\'s 24K gold price in Mumbai. The snippet includes both. Which is correct? Probably 
the first line "GoldPriceTodayinMumbaiis 16,215 Indian Rupee (INR)/gram24K." We\'ll use 16,215. Multiply 16,215 * 15 = 243,225 
INR cost price. Commission 5% = 12,161.25 INR.\n\nWe should also provide a structured result using GoldCommissionResult. 
Let\'s call the function to output structured result.'}]}, response_metadata={'model_name': 'openai/gpt-oss-120b', 
'id': 'gen-1778481765-OxLjqE7vxagJ3S8GCBsj', 'created': 1778481765, 'object': 'chat.completion', 'finish_reason': 'tool_calls', 
'logprobs': None, 'model_provider': 'openrouter'}, id='lc_run--019e15c6-1e35-74a0-931d-09a06aa9991f-0', 
tool_calls=[{'name': 'GoldCommissionResult', 'args': {'gold_price_per_gram': 16215, 'grams': 15, 'cost_price': 243225, 
'commission_rate': 0.05, 'commission_value': 12161.25}, 'id': 'chatcmpl-tool-9242b32b242f41efa62c40fd5d0e5343', 'type': 'tool_call'}], 
invalid_tool_calls=[], usage_metadata={'input_tokens': 751, 'output_tokens': 225, 'total_tokens': 976, 
'input_token_details': {'cache_read': 0, 'cache_creation': 0}, 'output_token_details': {'reasoning': 152}}), 
ToolMessage(content='Returning structured response: gold_price_per_gram=16215.0 grams=15 cost_price=243225.0 commission_rate=0.05 commission_value=12161.25', name='GoldCommissionResult', id='1c92da8d-4ac0-4c0c-a822-365427d5df38', 
tool_call_id='chatcmpl-tool-9242b32b242f41efa62c40fd5d0e5343')], 'structured_response': GoldCommissionResult(gold_price_per_gram=16215.0, 
grams=15, cost_price=243225.0, commission_rate=0.05, commission_value=12161.25)}
Answer: gold_price_per_gram=16215.0 grams=15 cost_price=243225.0 commission_rate=0.05 commission_value=12161.25

Points to note here

  1. Two tools are defined using the @tool decorator. In search tool DuckDuckGoSearchRun tool is used for doing the web search.
  2. Pydantic model class GoldCommissionResult is defined to instruct how the agent should structure its final output.
  3. In the create_agent function tools are configured as a list and Pydantic model class is wrapped with in the ToolStrategy class. With that agent runtime knows which tools are available and how to format the final response.
  4. In the attached output, go through the ToolMessage objects to see how interaction happens between the LLM and your code.

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


Related Topics

  1. Tools in LangChain With Examples
  2. Citation Aware RAG Application in LangChain
  3. LangChain Conversational RAG with Multi-user Sessions
  4. Embeddings in LangChain With Examples
  5. Vector Stores in LangChain With Examples

You may also like-

  1. Chain Using LangChain Expression Language With Examples
  2. Messages in LangChain
  3. Var type in Java - Local Variable Type Inference
  4. Java DelayQueue With Examples
  5. output() Function in Angular With Examples
  6. Python while Loop With Examples
  7. Strings in Python With Method Examples
  8. Index Route in React Router

Monday, May 11, 2026

Functional Interfaces in Java

A functional interface in Java is an interface that contains exactly one abstract method. A functional interface is also known as SAM type where SAM stands for (Single Abstract Method). They form the foundation for lambda expressions and method references, introduced in Java 8, making code more concise and expressive.

An example of functional interface with in Java would be Runnable interface which has only one method run().


Java functional interface example

interface IMyInterface {
  int getValue();
}

Here, IMyInterface qualifies as a functional interface because it defines only one abstract method getValue() (note that in an interface methods are implicitly abstract).

Radix Sort Program in Java

In this post we’ll explore how to implement Radix sort program in Java. Radix Sort belongs to the family of non-comparison-based sorting algorithms, similar to Counting Sort and Bucket Sort. It can achieve O(n) time complexity under certain conditions. It is particularly effective when sorting integers with a fixed number of digits.

How does Radix sort work

Radix sort works by doing the sorting in passes moving from least significant digit (LSD) to most significant digit (MSD). In each pass, a stable sorting algorithm (commonly Counting Sort) is applied to arrange elements based on the current digit.

If the maximum number in the array has d digits, Radix Sort performs d passes. The general logic can be expressed as:

for i = 1 to d
 Use any stable sort (like counting sort)
        to sort Arr on digit d

Following image shows how Radix sort sorts an input array in each pass. Here the maximum number is 655 so number of passes is 3.

radix sort in Java

Radix Sort Java program

Java program for Radix sort works on the following logic.

  1. Find the maximum number in the input array to determine the number of digits.
  2. Iterate through each digit of the maximum number, starting from the least significant digit.
  3. Sort the array on that digit using Counting sort.
  4. Repeat until all digits are processed, resulting in a fully sorted array.
public class RadixSort {

  public static void main(String[] args) {
    int[] arr = {80, 406, 21, 655, 55, 4, 8, 91, 87, 6};
    System.out.println("Original Array- " + Arrays.toString(arr));
    radixSort(arr);
    System.out.println("Sorted array after Radix sort- " + Arrays.toString(arr));
  }
    
  private static void radixSort(int[] arr){
    int max = getMaxElement(arr);
    int position = 1;
    while(max/position > 0){
      countingSort(arr, position);
      position *= 10;
    }        
  }
        
  private static int getMaxElement(int[] arr){
    int max = arr[0];
    for(int i = 1; i < arr.length; i++){
      if (arr[i] > max){
        max = arr[i];
      }
    }
    return max;
  }
    
  private static void countingSort(int[] arr, int position){
    int n = arr.length;
    int[] output = new int[n];
    int[] count = new int[n];
      
    //count number of times each element appear
    for(int i = 0; i < arr.length; i++){
      count[(arr[i]/position)%10]++;
    }

    // each element stores (element at current index+element
    // at previous index) to get the actual position of the element
    for(int i = 1; i < n; i++){
      count[i] = count[i] + count[i-1];
    }
  
    // for correct placement of the numbers start from the end
    for(int i = n-1; i >=0; i--){
      output[count[(arr[i]/position)%10] - 1] = arr[i];
      count[(arr[i]/position)%10]--;
    }
    // Copy output array to input to the input for 
    // the next stage of counting sort
    for(int i = 0; i < output.length; i++){
      arr[i] = output[i];
    }
    System.out.println("Counting sort at this stage " + Arrays.toString(arr));
  }
}

Output

Original Array- [80, 406, 21, 655, 55, 4, 8, 91, 87, 6]
Counting sort at this stage [80, 21, 91, 4, 655, 55, 406, 6, 87, 8]
Counting sort at this stage [4, 406, 6, 8, 21, 655, 55, 80, 87, 91]
Counting sort at this stage [4, 6, 8, 21, 55, 80, 87, 91, 406, 655]
Sorted array after Radix sort- [4, 6, 8, 21, 55, 80, 87, 91, 406, 655]

Performance of Radix Sort

If you are using Counting sort for sorting in each pass of Radix sort then time complexity of Radix sort is O(d*(n+k)). Here O(n+k) is the time complexity of counting sort and d is the number of passes over number having d digits.

Auxiliary space requirement is (n+k). Count array takes k space and the output array of the same size as input array is also used while sorting. Thus the space complexity of Radix sort is O(n+k).

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

>>>Return to Java Programs Page


Related Topics

  1. Bubble Sort Program in Java
  2. Quick Sort Program in Java
  3. Heap Sort Program in Java
  4. Java Program to Create Your Own BlockingQueue
  5. Java Program to Reverse a Number

You may also like-

  1. Reading File in Java Using Files.lines And Files.newBufferedReader
  2. How to Create PDF in Java Using OpenPDF
  3. Converting String to Enum Type in Java
  4. Java Program to Get All The Tables in a DB Schema
  5. Just In Time Compiler (JIT) in Java
  6. Reflection in Java - Getting Class Information
  7. String Vs StringBuffer Vs StringBuilder in Java
  8. Replica Placement Policy in Hadoop Framework

Friday, May 8, 2026

How to Loop Through a Map in Java

When working with collections, one common requirement is iterating over a Map implementation such as HashMap or Treemap in Java. Understanding how to loop through a Map in Java is essential for tasks like processing key‑value pairs, transforming data, or building efficient algorithms.

Methods for Iterating a Map

The Map interface provides three key methods to loop or iterate any Map implementation.

  • Set<Map.Entry<K, V>> entrySet()- This method returns a set of key‑value pairs. The entries in the set are actually object of type Map.Entry.
  • Set<K> keySet()- This method returns a set that contains all keys in the map.
  • Collection<V> values()- This method returns a Collection view of all values in the map.

These methods allow you to choose whether you want to iterate over entries, keys, or values. Let's see how these methods can be used to loop through a HashMap in Java.

  1. You can use either an iterator or a For-Each loop to iterate through a Map. See example.
  2. Java 8 onwards you can also use forEach statement. See example.

HashMap iteration using for-each and iterator Java example

In the example code HashMap is used to demonstrate traversal of a Map.

public class HashMapLooping {

 /**
  * @param args
  */
  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", "Newark");
  cityMap.put("4", "Newport");
  
  System.out.println("Looping with keySet");
  // Loop through HashMap using Key Set
  Set<String> citySet =  cityMap.keySet();
  for(String key : citySet){
   System.out.println("Key is " + key + " Value is " + cityMap.get(key));
  }
  
  System.out.println("Looping HashMap using entrySet");
  // Second way with entrySet
  for(Map.Entry<String, String> entry:  cityMap.entrySet()){
   System.out.println("Key is " + entry.getKey() + " Value is " + entry.getValue());
  }
  
  System.out.println("Looping with entrySet using Iterator");
  //Third way with iterator
  Iterator<Entry<String, String>> itr = cityMap.entrySet().iterator();
  while(itr.hasNext()){
   Map.Entry<String, String> entry = itr.next();
   System.out.println("Key is " + entry.getKey() + " Value is " + entry.getValue());
  }

  System.out.println("Looping HashMap using values method");
  for(String value : cityMap.values()){
    System.out.println("Value is " + value);
  }
 }
}

It can be seen that the first iteration of the HashMap is done using the keySet() method which gives a set of keys in the map. Using those keys respective values are retrieved. Since another call is required to get the mapped values this way of looping a HashMap is less efficient in case you need both keys and values.

Second iteration of the map is done using the entrySet() method which returns a set containing the Map.Entry objects. From Map.Entry object key and value can be retrieved using getKey() and getValue() methods.

Third way of iteration is again using the entrySet() method, only difference is instead of using the For-Each loop, iterator is used here.

Fourth way of iterating a HashMap uses the values() method and gives all the values stored in the HashMap.

Output of the program

Looping with keySet
Key is 1 Value is New York City
Key is 2 Value is New Delhi
Key is 3 Value is Newark
Key is 4 Value is Newport
Looping HashMap using entrySet
Key is 1 Value is New York City
Key is 2 Value is New Delhi
Key is 3 Value is Newark
Key is 4 Value is Newport
Looping with entrySet using Iterator
Key is 1 Value is New York City
Key is 2 Value is New Delhi
Key is 3 Value is Newark
Key is 4 Value is Newport
Looping using values method
Value is New York City
Value is New Delhi
Value is Newark
Value is Newport
Value is Kolkata

Iterating HashMap using forEach in Java

From Java 8 onward, the forEach method was introduced as part of the Map interface, allowing developers to iterate over a HashMap in a clean, functional style. Combined with lambda expressions and method references, this approach reduces iteration to a single, expressive statement. With forEach statement you can even iterate a HashMap directly without getting a collection view of the Map.

public class HashMapLooping {

 /**
  * @param args
  */
 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", "Newark");
  cityMap.put("4", "Newport");
  
  System.out.println("Looping with Lambda expression forEach stmt"); 
  Set<Map.Entry<String, String>> valueSet = cityMap.entrySet();
  valueSet.forEach((a)->System.out.println("Key is " + a.getKey() + 
           " Value is " + a.getValue()));
  
  System.out.println("Looping with method reference forEach");
  cityMap.entrySet().forEach(System.out::println);
  // Looping HashMap directly with forEach
  System.out.println("Looping HashMap with forEach statement");
  cityMap.forEach((K,V)->System.out.println("Key is " + K + " Value is " + V));
 }
}

Output

Looping with Lambda expression forEach stmt
Key is 1 Value is New York City
Key is 2 Value is New Delhi
Key is 3 Value is Newark
Key is 4 Value is Newport
Looping with method reference forEach
1=New York City
2=New Delhi
3=Newark
4=Newport
Looping HashMap with forEach statement
Key is 1 Value is New York City
Key is 2 Value is New Delhi
Key is 3 Value is Newark
Key is 4 Value is Newport
Key is 5 Value is Kolkata

đź’ĄPoints to note

  • A map can be iterated using entrySet() which returns a set containing objects of type Map.Entry.
  • Another way to iterate a map in Java is using keySet() method which returns a set containing keys of the map or values() method that returns a Collection view of the Map.
  • Map can be iterated either using iterator or for-each loop.
  • With Java 8 forEach statement provides a new way to loop a HashMap in Java.

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


Related Topics

  1. How HashMap Works Internally in Java
  2. How to Loop or Iterate an Arraylist in Java
  3. LinkedHashMap in Java With Examples
  4. How to Sort elements in different order in TreeSet using Comparator
  5. Java Collections Interview Questions And Answers

You may also like-

  1. Fail-Fast Vs Fail-Safe Iterator in Java
  2. Functional interfaces in Java 8
  3. Race condition in Java multi-threading
  4. Synchronization in Java - Synchronized Method And Block
  5. Difference Between Checked And Unchecked Exceptions in Java
  6. Callable and Future in Java With Examples
  7. Java Stream API Tutorial
  8. Encapsulation in Java

JavaScript Array and Object Destructuring

JavaScript destructuring assignment is a concise way to unpack values from arrays or properties from objects directly into variables. Introduced in ES6, destructuring makes code cleaner, reduces redundancy, and improves readability compared to traditional assignment methods.

Array Destructuring in JavaScript

const [India, USA, Japan] = ['Rupee', 'Dollar', 'Yen'];
console.log("Indian Currency - " + India); // Indian Currency - Rupee
console.log("American Currency - " + USA);// American Currency - Dollar
console.log("Japanese Currency - " + Japan);// Japanese Currency - Yen

Which is equivalent to this older approach of assigning array elements to variables.

const currencies = ['Rupee', 'Dollar', 'Yen'];
const India = currencies[0];
const USA = currencies[1];
const Japan = currencies[2];
console.log("Indian Currency - " + India);
console.log("American Currency - " + USA);
console.log("Japanese Currency - " + Japan);

As you can see, destructuring makes the code shorter and more expressive.

Extracting specific elements of an array

You don’t always need every element. By leaving a blank space with a comma for skipped values, you can selectively extract. For example, assigning only Rupee and Yen.

const currencies = ['Rupee', 'Dollar', 'Yen'];
const [India, , Japan] = currencies;

Using Destructuring when function returns an array

You can use destructuring to assign an array returned from a function to variables. Infact that's one of the most common uses of destructuring which you'll see in React.

For example useState() hook in React returns an array with exactly two values; current state and set function. Assignment for these two returned values can be done like this-

const [prevCount, setPrevCount] = useState(count);

Object destructuring in JavaScript

Object destructuring lets you pull properties directly into variables.

const obj = {first: 'Ramesh', last: 'Sharma', age: 35 };
const {first, last, age} = obj;
console.log(first); // Ramesh
console.log(last); // Sharma
console.log(age); // 35

Which is equivalent to this older approach of assigning object properties to variables.

const obj = {first: 'Ramesh', last: 'Sharma', age: 35 };
   
var f = obj.first;
var l = obj.last;
var ag = obj.age;

Assigning different names

When destructuring an object you have to use the same name for the variable as the mapped object key. If you want to use different names then you have to specify those names explicitly.

//specify new name after colon
const { first: firstName, last: lastName, age} = obj;
console.log(firstName);
console.log(lastName);
console.log(age);

Extracting specific properties of an object

You can extract specific properties of an object by giving just the needed keys. For example, if you need only first and age.

const obj = {first: 'Ramesh', last: 'Sharma', age: 35 };
const {first, age} = obj;

Passing destructured object as function arguments

If you have a function that takes object as an argument then you can pass the destructured object as function arguments to make your function more readable.

// function taking params as destructuring
function displayPerson({first, last, age}){
  console.log("first ", first, "last ", last, "age ", age)
}

That's where you will see its usage in React, to destructure props object.

In calling component-

<Person first="Ramesh" last="Sharma" age=35 />

Person Component with props

const Person = (props) => {
  return(
    <h2>{props.first} {props.last} {props.age}</h2>
  );
}

Same thing with props destructuring

const Person = ({first, last, age}) => {
  return(
    <h2>{first} {last} {age}</h2>
  );
}

Why Use JavaScript Array and Object Destructuring

  1. Cleaner syntax- Requires fewer lines of code.
  2. Improved readability- It is instantly clear which value is being extracted.
  3. Flexibility- Provides flexibility to skip values, rename properties, set default values.
  4. Modern best practice- Widely used in frameworks like React, Node.js, and Next.js.

That's all for this topic JavaScript Array and Object Destructuring. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. JavaScript Spread Operator
  2. JavaScript let and const With Examples
  3. JavaScript Arrow Function With Examples
  4. React HelloWorld App - First React App
  5. React Declarative Approach

You may also like-

  1. What Are JVM, JRE And JDK in Java
  2. Java Record Class With Examples
  3. React Virtual DOM
  4. Controlled and Uncontrolled Components in React
  5. Angular Cross Component Communication Using Subject Observable
  6. Angular Property Binding With Examples
  7. First LangChain Program: Ask Me Anything
  8. Dependency Injection Using factory-method in Spring

Java DelayQueue With Examples

DelayQueue in Java is an implementation of BlockingQueue interface introduced in Java 5 as part of the java.util.concurrent package. Alongside other concurrent utilities like CyclicBarrier, Exchanger, ConcurentSkipListMap, CopyOnWriteArraySet, it provides developers with advanced concurrency tools for building scalable applications.

DelayQueue is Unbounded

The DelayQueue in Java is an unbounded implementation of BlockingQueue, that's where it is different from the other implementations of BlockingQueue like ArrayBlockingQueue (Always bounded) and LinkedBlockingQueue (both bounded and unbounded options). Though it is similar to PriorityBlockingQueue in this behaviour as PriorityBlockingQueue is also unbounded.

DelayQueue stores Delayed elements

DelayQueue in Java is a special implementation of BlockingQueue as it can only store elements of type Delayed and an element can only be retrieved from DelayQueue when its delay has expired.

Delayed interface which defines the type for the elements in the DelayQueue has one method of its own:

  1. getDelay(TimeUnit unit)- Returns the remaining delay associated with this object, in the given time unit.

Delayed interface also extends Comparable interface so compareTo(T o) method should also be implemented. This method implementation will decide whether you want to retrieve elements in ascending order of delay or descending.

According to JavaDocs "An implementation of this interface must define a compareTo method that provides an ordering consistent with its getDelay method."

So, just to sum it up; DelayQueue stores elements of type Delayed. When you implement Delayed interface two methods have to be implemented getDelay(TimeUnit unit) and compareTo(T o).

Ordering in Java DelayQueue

  1. DelayQueue orders its elements (of type Delayed) based on the remaining delay associated with the element as returned by the getDelay() method.
  2. The head of the queue is the Delayed element whose delay expired earliest.
  3. The tail of the queue is the Delayed element with the longest remaining delay.

This makes DelayQueue ideal for task scheduling, caching with expiration, and delayed message processing.

Producer Consumer Java example using DelayQueue

Let's create a producer consumer using the DelayQueue. There is also a class DelayClass which implements Delayed interface and implements the required methods- getDelay() and compareTo(). DelayQueue will store objects of DelayClass.

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class DelayQDemo {
  public static void main(String[] args) {
    // delay of 2 seconds
    final long delay = 2000;
    BlockingQueue<DelayClass> delayQ = new DelayQueue<DelayClass>();
      
    // Producer thread
    new Thread(){
      @Override
      public void run() {
        for(int i = 0; i < 5; i++){
          try {
            // putting elements in delay queue
            delayQ.put(new DelayClass("item"+i, delay));
            Thread.sleep(50);
          } catch (InterruptedException e) {
            System.out.println("Error while putting values in the Queue "
             + e.getMessage());
          }
        }
      }
    }.start();
      
    // Consumer thread
    new Thread(){
      @Override
      public void run() {
        for(int i = 0; i < 5; i++){
          try {
            // retrieving elements from delay queue
            System.out.println(" Consumer got - " + delayQ.take());
            Thread.sleep(500);
          } catch (InterruptedException e) {
            System.out.println("Error while retrieving value from the Queue "
             + e.getMessage());
          }
        }
      }
    }.start();
  }
}

// Delayed interface implementing class
class DelayClass implements Delayed{
  private String item;
  private long expireTime;
  DelayClass(String item, long delay){
    this.item = item;
    // Expiretime is currenttime+delay, so if delay of 2 sec is required
    // expiration from queue will hppn after
    // currenttime + 2 sec
    this.expireTime = System.currentTimeMillis() + delay;
  }
    
  @Override
  public long getDelay(TimeUnit unit) {
    long diff = expireTime - System.currentTimeMillis();
    return unit.convert(diff, TimeUnit.MILLISECONDS);
  }
    
  @Override
  public int compareTo(Delayed o) {
    if(this.getDelay(TimeUnit.MILLISECONDS) < o.getDelay(TimeUnit.MILLISECONDS)){
      return -1;
    }
    if(this.getDelay(TimeUnit.MILLISECONDS) > o.getDelay(TimeUnit.MILLISECONDS)){
      return 1;
    }
    return 0;        
  }
    
  public String toString(){
    return "item = " + item + " expireTime = " + expireTime;
  } 
}

Output

Consumer got - item = item0 expireTime = 1458998017469
Consumer got - item = item1 expireTime = 1458998017531
Consumer got - item = item2 expireTime = 1458998017594
Consumer got - item = item3 expireTime = 1458998017656
Consumer got - item = item4 expireTime = 1458998017719

Here it can be seen elements are retrieved from the queue only after the delay expires.

đź’ĄPoints to remember

  1. DelayQueue in Java stores element of type Delayed.
  2. Element is retrieved from DelayQueue only when its delay has expired.
  3. The head of the queue is that Delayed element whose delay expired furthest in the past.
  4. If no delay has expired there is no head and poll will return null.
  5. Expiration occurs when an element's getDelay(TimeUnit tu) method returns a value less than or equal to zero.

Reference: https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/concurrent/DelayQueue.html

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


Related Topics

  1. Java SynchronousQueue With Examples
  2. Java BlockingDeque With Examples
  3. Java LinkedTransferQueue With Examples
  4. Java ReentrantReadWriteLock With Examples
  5. Java Semaphore With Examples

You may also like-

  1. ConcurrentHashMap in Java With Examples
  2. Deadlock in Java Multi-Threading
  3. Synchronization in Java - Synchronized Method And Block
  4. Java Collections Interview Questions And Answers
  5. Java Lambda Expression And Variable Scope
  6. Autowiring in Spring Using @Autowired and @Inject Annotations
  7. Try-With-Resources in Java With Examples
  8. Java Program to Find The Longest Palindrome in a Given String

Thursday, May 7, 2026

pass Statement in Python

The pass statement in Python is a simple yet powerful tool that acts as a placeholder in your code. It performs no action when executed, but ensures that your program remains syntactically correct. This makes it especially useful when you want to define the structure of your code without implementing the logic right away.

Python pass statement

  • The pass statement is a null operation, when it is executed, nothing happens.
  • It is often used in places where a statement is required syntactically, but you don’t want to perform any operation yet.
  • Common use cases include empty functions, classes, loops, or conditional blocks that you plan to implement later.

Using pass in a Loop

If you have an array of numbers and you want to display only those numbers which are less than 100.

numbers = [89, 102, 45, 234, 67, 10, 333, 32]
for num in numbers:
  if num > 100:
    #do nothing
    pass
  else:
    print('number is', num)

Output

number is 89
number is 45
number is 67
number is 10
number is 32

In the above example, if-else statement checks whether each number in the list is greater than 100 or not. In case it is then you do nothing and that is explicitly indicated using the pass statement.

In most cases, you can write Python code without explicitly using the pass statement. However, including it often improves readability and makes your intent clear to other developers. The pass statement ensures that your code remains syntactically valid and prevents errors such as IndentationError when leaving a block empty.

Using pass in Classes

Suppose there is a Person class where you have a method to display Person data and retrieve person data. You are planning to implement retrieveData() method later, that will fetch Person details from DB, so you keep the method in place as a TODO reminder.

class Person:
    def __init__(self, name, age):
        print('init called')
        self.name = name
        self.age = age

    def display(self):
        print('in display')
        print("Name-", self.name)
        print("Age-", self.age)

    def retrieveData(self):
        #TODO has to be implemented to fetch details from DB

person = Person('John', 40)
person.display()

But running this class gives an error “IndentationError: expected an indented block

In such case adding pass statement with unimplemented method ensures that IndentationError is not thrown.

    def retrieveData(self):
        #TODO has to be implemented to fetch details from DB
        pass

So, you can see that Python pass statement can be used where you need a place holder be it with in a for loop, while loop or if-else statement, after def or even after class and in exception handling too.

pass statement with class Inheritance

If you are creating a user‑defined exception class by extending Python’s built‑in Exception class without adding new behavior, you can simply use pass statement.

class MyException(Exception):
    pass

pass Statement in Exception Handling

If you want to catch a specific exception but don't want to take any action after catching it, you can use pass statement to express that intent.

numbers = [89, 102, 0, 234, 67, 10, 333, 32]
for num in numbers:
    try:
        result = 1000/num
        print('Result is',result)
    except ZeroDivisionError:
        print('Division by Zero')
        result = 0
    except AttributeError:
        pass

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

>>>Return to Python Tutorial Page


Related Topics

  1. Python assert Statement
  2. Python Exception Handling Tutorial
  3. Global Keyword in Python With Examples
  4. Abstraction in Python
  5. Difference Between Function and Method in Python

You may also like-

  1. Comparing Two Strings in Python
  2. Namespace And Variable Scope in Python
  3. Passing Object of The Class as Parameter in Python
  4. Python Program to Find Factorial of a Number
  5. What Are JVM, JRE And JDK in Java
  6. Java Program to Detect And Remove Loop in a Linked List
  7. How to Read Input From Console in Java
  8. Word Count MapReduce Program in Hadoop