Sunday, April 5, 2026

Java Lambda Expression as Method Parameter

In this guide, we’ll explore how to use a Java Lambda Expression as Method Parameter. Lambda expressions provide a concise way to implement the abstract method of a functional interface, making code cleaner and more expressive. Since the target type of a lambda is always a functional interface, you can pass a lambda wherever such an interface is expected, including as a method argument. To pass a lambda expression as a method parameter in Java, the type of the method argument, which receives the lambda expression as a parameter, must be of functional interface type.

Why Pass Lambda Expressions as Parameters

Using a Java Lambda Expression as Method Parameter allows developers to write flexible and reusable methods. Instead of hard‑coding behavior, you can pass custom logic directly into a method, reducing boilerplate and improving readability. This is especially useful in APIs like Java’s Collections framework and Stream API, where lambdas are frequently used for filtering, mapping, and sorting.

Counting Sort Program in Java

In this tutorial, we’ll walk through how to implement a Counting Sort Program in Java. Counting Sort is a linear‑time sorting algorithm with a time complexity of O(N + K), making it faster than comparison‑based algorithms such as Merge sort and Quick sort when the input range is limited. It belongs to the family of non‑comparison sorting techniques, alongside Radix Sort and Bucket Sort.

Advantages and Limitations

Though counting sort is one of the fastest sorting algorithm but it has certain drawbacks too. One of them is that the algorithm requires prior knowledge of the input range. Counting sort also needs auxiliary space as it needs to store the frequency of elements. This makes it less memory‑efficient for datasets with very large ranges.

How does counting sort work

Counting sort works by counting the frequency of each element to create a frequency array or count array. Then these counts are used to compute the index of an element in the sorted array. The process can be broken down into following steps:

  1. Initialize Count Array
    Create a count array to store the frequency count of each element. If the range of elements is 0 to k then count array should be of length k+1. For example, if max element in the array is 15 then count array should be of length 16.
  2. Populate Frequency Counts
    Iterate through the elements in input array and for each element increment its count in the corresponding index in the count array.
    For example, if input array is- [0, 4, 2, 6, 5, 4, 8, 9, 8, 6]

    Then the count array would be like below-

    Counting sort
  3. Compute Prefix Sums
    Transform the count array so that each index stores the sum of element at current index + element at previous index (prefix sum array).
    Counting sort Java
  4. Build Sorted Output
    Using this modified count array you need to construct the sorted array. For that you take an element from the input array and go to that index in the modified count array to get a value. That value is the place, of the element picked from the input array, in the sorted array.
    In the count array decrement the value by 1 too.

    For example if input array and modified count array are as follows-

    First element in the input array is 0, so consult the 0th index in the count array which is 1. That means 0 goes at the place 1 (i.e. index 0) in the sorted array. Decrement the value in the count array too. In this step value at index 0 in the count array will be decremented by 1 so that it becomes 0.

    Second element in the input array is 4, so consult the 4th index in the count array which is 4. That means 4 goes at the place 4 (i.e. index 3) in the sorted array. With in input array an element may be repeated and those should be grouped together. For that we need to decrement the value in the count array. In this step value at index 4 in the count array will be decremented by 1 so that it becomes 3.

    When the next 4 is encountered in the input array value at the 4th index in the count array will be 3. That means next 4 goes at the place 3 (i.e. index 2) in the sorted array.

    Counting Sort Java Program

Counting Sort Java program

public class CountingSort {

  public static void main(String[] args) {
    int[] arr = {0, 4, 2, 6, 5, 4, 8, 9, 8, 6};
    // max element + 1
    int range = 10;
    System.out.println("Original Array- " + Arrays.toString(arr));
    arr = countingSort(arr, range);
    System.out.println("Sorted array after counting sort- " + Arrays.toString(arr));
  }
    
  private static int[] countingSort(int[] arr, int range){
    int[] output = new int[arr.length];
    int[] count = new int[range];
    //count number of times each element appear
    for(int i = 0; i < arr.length; i++){
      count[arr[i]]++;
    }
    System.out.println("Count array- " + Arrays.toString(count));
    // each element stores (sum of element at current index 
    //+ element at previous index)
    for(int i = 1; i < range; i++){
      count[i] = count[i] + count[i-1];
    }
    System.out.println("Modified count- " + Arrays.toString(count));
    for(int i = 0; i < arr.length; i++){
      output[count[arr[i]] - 1] = arr[i];
      count[arr[i]]--;
    }
    return output;
  }
}

Output

Original Array- [0, 4, 2, 6, 5, 4, 8, 9, 8, 6]
Count array- [1, 0, 1, 0, 2, 1, 2, 0, 2, 1]
Modified count- [1, 1, 2, 2, 4, 5, 7, 7, 9, 10]
Sorted array after counting sort- [0, 2, 4, 4, 5, 6, 6, 8, 8, 9]

Performance of Counting Sort

If the number of elements to be sorted is n and the range of elements is 0-k then the time complexity of Counting sort can be calculated as-

Loop to create count array takes O(n) time. Second loop where count array is modified takes O(k) time and creating sorted output array again takes O(n) time. Thus the time complexity with all these combined comes as O(2n+k). Since constants are not taken into consideration so the time complexity of Counting sort is O(n+k).

Auxiliary space requirement is also (n+k). Count array takes k space and the output array n. Thus the space complexity of Counting sort is O(n+k).

That's all for this topic Counting 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. Shell Sort Program in Java
  2. Heap Sort Program in Java
  3. Insertion Sort Program in Java
  4. How to Read Input From Console in Java
  5. How to Create Password Protected Zip File in Java

You may also like-

  1. Check if Given String or Number is a Palindrome Java Program
  2. Remove Duplicate Elements From an Array in Java
  3. Difference Between Two Dates in Java
  4. Java Program to Check Prime Number
  5. TreeSet in Java With Examples
  6. Java CyclicBarrier With Examples
  7. Java Variable Types With Examples
  8. Circular Dependency in Spring Framework

RunableSequence in LangChain With Examples

RunnableSequence in LangChain is a sequence of Runnable objects, where the output of one is the input of the next. You can use it by using the pipe (|) operator where either the left or right operands (or both) must be a Runnable or RunnableSequence can be instantiated directly.

LangChain RunnableSequence Example

Let's say you have been given a task of creating an automated workflow to analyze a contract snippet, identify risks, and summarize them to be used for legal or finance department.

You want to create a workflow where-

  1. First you send the contract to the model to analyze it for any risks.
  2. Then send that risk analysis to the model to create a summarized memo.

Required Packages

  • python-dotenv
  • langchain
  • langchain-google-genai
  • langchain-ollama

For Gemini model you need the set the GEMINI_API_KEY in the .env file which can then be loaded as an environment variable using load_dotenv() function.

First let see the example where pipe operator (|) is used to create a sequence of actions.

Example 1: Using piped workflow

from langchain_core.prompts import PromptTemplate
from langchain_core.runnables import RunnableSequence
from langchain_core.output_parsers import StrOutputParser
from langchain_ollama import ChatOllama
from langchain_google_genai import ChatGoogleGenerativeAI
from dotenv import load_dotenv

load_dotenv()

# 1. Define LLM
#llm = ChatOllama(model="llama3.1", temperature=0)

llm = ChatGoogleGenerativeAI(model="gemini-3.1-flash-lite-preview", temperature=0)

# Define the prompts
prompt_1 = PromptTemplate.from_template(
    "Analyze the following contract clause for any hidden financial risks: {clause}"
)
prompt_2 = PromptTemplate.from_template(
    "Summarize the following risk analysis in a professional, concise, bulleted memo for the financial head: {analysis}"
)

#Parsing to String ensures clean text outputs
parser = StrOutputParser()

# 4. Create Sequence: Clause -> Risk Analysis -> Financial Team 
# (gets analysis as input and produces memo for financial head as output)
# Sequence is: Prompt1 -> LLM -> Parser -> Prompt2 -> LLM -> Parser
chain = (
    {"analysis": prompt_1 | llm | parser} 
    | prompt_2 
    | llm 
    | parser
)

# Execute with contract 
contract_clauses = """
Scope of Work (SOW):Vendor shall deliver required work with in one month of initiation and provide support services as detailed in Exhibit A.
Payment Terms: Client shall pay Invoice within 30 days of receipt. Late payments will incur a 1.5% monthly interest fee.
Termination Clause: Either party may terminate this agreement with 10 calendar days' written notice if the other party breaches material terms.
Limitation of Liability: The vendor will not be liable for any damages unless they exceed 300% of the total contract value, and notice is provided within 1 day.
"""
result = chain.invoke({"clause": contract_clauses})
print(result)

Which gives memorandum as output, here are few lines of the output.

Output

**MEMORANDUM**

**TO:** Head of Finance
**FROM:** [Your Name/Department]
**DATE:** October 26, 2023
**SUBJECT:** Risk Assessment: Proposed Vendor Contract

I have completed a risk analysis of the proposed vendor contract. The current draft is heavily skewed in favor of the vendor and contains several provisions that expose the company to significant, avoidable financial liability.

### **Key Risk Areas**

*   **Scope of Work (SOW):** The lack of defined support parameters in "Exhibit A" creates an open-ended financial liability, leaving us vulnerable to aggressive "out-of-scope" billing.
....
....

Example 2: Using RunnableSequence Explicitly

You can explicitly use RunnableSequence that makes the workflow more transparent and modular, which is useful when debugging or extending complex pipelines. The above example can be modified to use RunnableSequence instead.

from langchain_core.prompts import PromptTemplate
from langchain_core.runnables import RunnableSequence
from langchain_core.output_parsers import StrOutputParser
from langchain_ollama import ChatOllama
from langchain_google_genai import ChatGoogleGenerativeAI
from dotenv import load_dotenv

load_dotenv()

# 1. Define LLM
llm = ChatOllama(model="llama3.1", temperature=0)

#llm = ChatGoogleGenerativeAI(model="gemini-3.1-flash-lite-preview", temperature=0)

# Define the prompts
prompt_1 = PromptTemplate.from_template(
    "Analyze the following contract clause for any hidden financial risks: {clause}"
)
prompt_2 = PromptTemplate.from_template(
    "Summarize the following risk analysis in a professional, concise, bulleted memo for the financial head: {analysis}"
)

#Parsing to String ensures clean text outputs
parser = StrOutputParser()

# Step A: Clause -> Risk Analysis
risk_analysis_chain = RunnableSequence(prompt_1, llm, parser)

# Step B: Risk Analysis -> Financial Memo
financial_memo_chain = RunnableSequence(prompt_2, llm, parser)
# Step C: Full pipeline
chain = RunnableSequence(
        {"analysis": risk_analysis_chain},  # feed clause into risk analysis
        financial_memo_chain                # feed analysis into financial memo    
)

# Execute with Corporate Input
contract_clauses = """
Scope of Work (SOW):Vendor shall deliver required work with in one month of initiation and provide support services as detailed in Exhibit A.
Payment Terms: Client shall pay Invoice within 30 days of receipt. Late payments will incur a 1.5% monthly interest fee.
Termination Clause: Either party may terminate this agreement with 10 calendar days' written notice if the other party breaches material terms.
Limitation of Liability: The vendor will not be liable for any damages unless they exceed 300% of the total contract value, and notice is provided within 1 day.
"""
result = chain.invoke({"clause": contract_clauses})

print(result)

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


Related Topics

  1. What is LangChain - An Introduction
  2. LangChain PromptTemplate + Streamlit - Code Generator Example
  3. RunablePassthrough in LangChain With Examples
  4. RunnableLambda in LangChain With Examples
  5. RunnableBranch in LangChain With Examples

You may also like-

  1. String in Java Tutorial
  2. Array in Java
  3. Count Number of Words in a String Java Program
  4. Ternary Operator in Java With Examples
  5. Java Multithreading Interview Questions And Answers
  6. Java Exception Handling Tutorial
  7. ConcurrentHashMap in Java With Examples
  8. TreeMap in Java With Examples

Saturday, April 4, 2026

RunablePassthrough in LangChain With Examples

RunablePassthrough in LangChain is a simple runnable that returns its input unchanged. It is used in the scenario where you want to preserve the original input alongside other computed values.

For example, if you have a RAG pipeline like this-

chain = (
    {"context": retriever, "question": RunnablePassthrough()}
    | prompt
    | model
    | StrOutputParser()
)

Here you have to send question to the vector store as well as to the prompt later in the pipeline. Using "question": RunnablePassthrough() ensures the original question is retained for the prompt, whereas without it the "question" key would not be available during prompt construction.

LangChain RunnablePassthrough Example

Let’s say you are creating a RAG-based Customer Support Bot that retrieves documentation from the vector store, enriches the prompt with that context, and passes the original question along then you can use RunnablePassthrough, to preserve the question, to be used later in the pipeline.

Here are few snippets of the code (full vector store is not implemented here, just the relevant part to keep focus on RunnablePassthrough). Pinecone vector store is used for indexing and storing vector embeddings.

from langchain_openai import OpenAIEmbeddings, ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.schema import StrOutputParser
from langchain_pinecone import PineconeVectorStore
from pinecone import Pinecone
from langchain.schema.runnable import RunnablePassthrough, RunnableLambda

embeddings = OpenAIEmbeddings()
doc_search = PineconeVectorStore.from_existing_index(index, embeddings)
retriever = doc_search.as_retriever(search_kwargs={"k": 2})

# Define the Prompt Template
template = "Answer the question based only on the following context:
{context}

Question: {question}
"
prompt = ChatPromptTemplate.from_template(template)
model = ChatOpenAI()

# Build the Chain
# Use RunnableLambda to ensure the retriever gets the 'question' key
chain = (
    {
        "context": RunnableLambda(lambda x: retriever.invoke(x["question"])),
        "question": RunnablePassthrough()
    }
    | prompt
    | model
    | StrOutputParser()
)

# Run the chain
response = chain.invoke({"question": "When is the report due for environment policy?"})
print(response)

RunnablePassthrough.assign in LangChain

RunablePassthrough.assign lets you add extra static or computed fields to the passthrough output.

For example, suppose you want to add some metadata like timestamp to the prompt which is then passed to the LLM as extra context for guiding the model’s response.

# Define the Prompt Template 
template = """ Answer the question based only on the following context:
{context}

Question: {question}

Metadata: {timestamp}

Use the metadata to guide your response. For example, consider the timestamp when deciding if the information is current or relevant.
"""

In chain you can pass this timestamp information using RunnablePassthrough().assign

# 3. Build the Chain
chain = (
    {
        "context": RunnableLambda(lambda x: retriever.invoke(x["question"])),
        # Preserve the question AND add metadata with .assign
        "question": RunnablePassthrough().assign(
            timestamp=lambda x: datetime.now().isoformat()
        )
    }
    | prompt
    | model
    | StrOutputParser()
)

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


Related Topics

  1. RunnableParallel in LangChain With Examples
  2. RunnableLambda in LangChain With Examples
  3. RunnableBranch in LangChain With Examples
  4. Chain Using LangChain Expression Language With Examples
  5. LangChain PromptTemplate + Streamlit - Code Generator Example

You may also like-

  1. String in Java Tutorial
  2. Array in Java
  3. Count Number of Words in a String Java Program
  4. Ternary Operator in Java With Examples
  5. Java Multithreading Interview Questions And Answers
  6. Java Exception Handling Tutorial
  7. ConcurrentHashMap in Java With Examples
  8. TreeMap in Java With Examples

Friday, April 3, 2026

Java BufferedWriter Class With Examples

The Java BufferedWriter class is part of the java.io package and is widely used to write text efficiently to character‑output streams. Instead of writing characters directly to a file or output stream, BufferedWriter acts as a wrapper around a Writer (such as FileWriter or OutputStreamWriter) whose write() operations may be costly. BufferedWriter makes the write operation more efficient by buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

Without buffering, every call to write() or print() would immediately convert characters into bytes and push them to the file system, which is inefficient. By using Java BufferedWriter, you reduce costly I/O operations and achieve faster, smoother file writing.

Java BufferedWriter constructors

  • BufferedWriter(Writer out)- Wraps the passed Writer and creates a buffering character-input stream that uses a default-sized input buffer. Default buffer size for BufferedWriter is 8192 bytes i.e. 8 KB.

    For example-

     BufferedWriter out = new BufferedWriter(new FileWriter("resources/abc.txt"));
     
  • BufferedWriter(Writer out, int sz)- Wraps the passed Writer and creates a new buffered character-output stream that uses an output buffer of the given size.

Java BufferedWriter methods

Methods in BufferedWriter class are as given below-

  • flush()- Flushes the stream.
  • newLine()- Writes a line separator.
  • write(int c)- Writes a single character.
  • write(char[] cbuf, int off, int len)- Writes a portion of an array of characters. Parameter off is the offset from which to start reading characters and parameter len is the number of characters to write.
  • write(String s, int off, int len)- Writes a portion of a String. Parameter off is the offset from which to start reading characters and parameter len is the number of characters to write.

Java BufferedWriter examples

For using BufferedWriter steps are as follows-

  1. Create an instance of BufferedWriter wrapped around another Writer.
  2. Using that instance to write to a file.
  3. Close the stream, you should close the resources in finally block or you can use try-with-resources to automatically manage resources.

1. Using write(int c) method of the Java BufferedWriter class to write single character to a file.

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class FileWriteRW {
  public static void main(String[] args) throws IOException {
    try (BufferedWriter bw = new BufferedWriter(new FileWriter("F:\\Temp\\write.txt"))){
      bw.write(65); //writes A
      bw.write(66); //writes B
      bw.write(67); //writes C
    }
  }
}

2. Using write(char[] cbuf, int off, int len) method of the Java BufferedWriter class to write portion of a character array.

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class FileWriteRW {
  public static void main(String[] args) throws IOException {
    String str = "This is a test String";
    char[] buffer = str.toCharArray();
    try (BufferedWriter bw = new BufferedWriter(new FileWriter("F:\\Temp\\write.txt"))){
      bw.write(buffer, 0, 7);// takes portion from index 0..6
    }
  }
}

3. Using write(String s, int off, int len) of the Java BufferedWriter class to write a portion of a String.

public class FileWriteRW {
  public static void main(String[] args) throws IOException {
    String str = "This is a test String";
    try (BufferedWriter bw = new BufferedWriter(new FileWriter("F:\\Temp\\write.txt"))){
      bw.write(str, 0, 7);// takes substring from index 0..6
    }
  }
}

4. Using newLine() method of the Java BufferedWriter class.

public class FileWriteRW {
  public static void main(String[] args) throws IOException {
    String str = "This is a test String";
    try (BufferedWriter bw = new BufferedWriter(new FileWriter("F:\\Temp\\write.txt"))){
      bw.write(str, 0, 7);// takes substring from index 0..6
      bw.newLine(); // new line
      bw.write(str, 7, str.length()-7);
      bw.flush(); // flushes the stream
    }
  }
}

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

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Character Streams in Java IO
  2. Byte Streams in Java IO
  3. Write to a File in Java
  4. How to Append to a File in Java
  5. Reading File in Java Using Files.lines And Files.newBufferedReader

You may also like-

  1. How to Read File From The Last Line in Java
  2. Difference Between Thread And Process in Java
  3. LinkedHashSet in Java With Examples
  4. String Vs StringBuffer Vs StringBuilder in Java
  5. Constructor Overloading in Java
  6. Python Program to Display Fibonacci Series
  7. Spring MVC Exception Handling Example Using @ExceptionHandler And @ControllerAdvice
  8. Lazy Initialization in Spring Using lazy-init And @Lazy Annotation

How to Sort ArrayList in Java

When you create an ArrayList in Java, elements are stored in the order they are inserted. By default, iterating over the list will display items in this insertion order. However, in real-world applications you often need to sort an ArrayList in Java, whether alphabetically, numerically, or by custom rules such as dates or objects.

In this tutorial, we’ll explore how to sort ArrayList in Java using different approaches available in Java. We’ll cover sorting Strings, Integers, and Dates in both ascending and descending order.


Options for sorting a List

Java provides multiple ways to sort a list:

  1. Using List.sort() (Java 8 and later)


    The sort() method was introduced as a default interface method in the List interface. It allows you to sort directly without using external utilities.

    list.sort(Comparator.naturalOrder());   // Ascending order
    list.sort(Comparator.reverseOrder());   // Descending order
    
    Method signature
    default void sort(Comparator<? super E> c)- If the comparator is null, elements must implement Comparable, and natural ordering will be applied.
  2. Using Collections.sort() method


    The traditional way to sort an ArrayList is via the Collections utility class. There are two overloaded versions of sort method and according to Java docs their description is-
    • public static <T extends Comparable<? super T>> void sort(List<T> list)- Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface. Furthermore, all elements in the list must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list).
    • public static <T> void sort(List<T> list, Comparator<? super T> c)- Sorts the specified list according to the order induced by the specified comparator. All elements in the list must be mutually comparable using the specified comparator (that is, c.compare(e1, e2)must not throw a ClassCastException for any elements e1 and e2 in the list).
    Usage-
    Collections.sort(list); // Natural ascending order
    Collections.sort(list, Comparator.reverseOrder()); // Custom order
    
  3. Using Java Stream API

    Using sorted method of the Java Stream API which provides a functional approach to sorting, especially useful when you want a sorted view without modifying the original list. There are two overloaded variants of the sorted method.
    • sorted()- Returns a stream consisting of the elements of this stream, sorted according to natural order.
    • sorted(Comparator<? super T> comparator)- Returns a stream consisting of the elements of this stream, sorted according to the provided Comparator.

Sorting ArrayList of strings using sort() method of List

public class SortListDemo {
  public static void main(String[] args) {
    List<String> cityList = new ArrayList<>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Bangalore");
    cityList.add("Chennai");
    cityList.add("Kolkata");
    cityList.add("Mumbai");
    // Passing null so natural ordering is used
    cityList.sort(null);
    System.out.println("List sorted using natural ordering" + cityList);
    
    // Using naturalOrder method to sort in natural order
    cityList.sort(Comparator.naturalOrder());
    System.out.println("List sorted using natural ordering" + cityList);
    
    // Using reverseOrder method to impose reverse of natural ordering
    cityList.sort(Comparator.reverseOrder());
    System.out.println("List sorted in reverse" + cityList);
  }
}

Output

List sorted using natural ordering[Bangalore, Chennai, Delhi, Kolkata, Mumbai, Mumbai]
List sorted using natural ordering[Bangalore, Chennai, Delhi, Kolkata, Mumbai, Mumbai]
List sorted in reverse[Mumbai, Mumbai, Kolkata, Delhi, Chennai, Bangalore]

Using Collections.sort() method to sort ArrayList

To sort an ArrayList of strings according to the natural ordering of its elements we can use the first of the two sort methods.

Collections.sort(List<T> list)
public class SortListDemo {
  public static void main(String[] args) {
    List<String> cityList = Arrays.asList("Delhi","Mumbai","Bangalore","Chennai","Kolkata","Mumbai");
    // sorting the list
    Collections.sort(cityList);
    System.out.println("List sorted using natural ordering" + cityList);
  }
}

Output

List sorted using natural ordering[Bangalore, Chennai, Delhi, Kolkata, Mumbai, Mumbai]

As you can see you just need to pass the ArrayList to sort method. Collections.sort will work in this case because String class implements Comparable interface and provides implementation for the method compareTo(String anotherString).

Same way Integer class or Date class also implements Comparable interface so list of integers (or dates) can also be sorted in natural order by using sort() method of the Collections class or by using sort() method of the List interface. In fact Java docs give a list of all the classes that implements comparable interface thus can be used with the sort method to sort the elements in the natural order.

Classes Implementing Comparable

Following is the list of classes that already implement Comparable interface in Java. Thus the ArrayList storing obejcts of any of these classes can be sorted in its natural ordering by passing the list to sort() method.

Class Natural Ordering
Byte Signed numerical
Character Unsigned numerical
Long Signed numerical
Integer Signed numerical
Short Signed numerical
Double Signed numerical
Float Signed numerical
BigInteger Signed numerical
BigDecimal Signed numerical
Boolean Boolean.FALSE < Boolean.TRUE
File System-dependent lexicographic on path name
String Lexicographic
Date Chronological
CollationKey Locale-specific lexicographic

Sorting an ArrayList of strings in descending order

Collections.sort() method always sorts ArrayList of strings in ascending order. For sorting an ArrayList in descending order you need to use the second sort method which takes two parameters. First is the list that has to be sorted and second a comparator class that can be used to allow precise control over the sort order.
For sorting an ArrayList in descending order there are two options,

  • Use method reverseOrder() provided by Collections class itself

    General form and description

    public static <T> Comparator<T> reverseOrder()
    
    Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.
  • Using a custom comparator.

Sorting ArrayList in descending order using reverseOrder method

public class SortListDemo {
  public static void main(String[] args) {
    List<String> cityList = Arrays.asList("Delhi","Mumbai","Bangalore","Chennai","Kolkata","Mumbai");
     // sorting the list in descending order
    Collections.sort(cityList, Collections.reverseOrder());
    System.out.println("List sorted in reverses order- " + cityList);
  }
}

Output

List sorted in reverses order- [Mumbai, Mumbai, Kolkata, Delhi, Chennai, Bangalore]

Sorting ArrayList in descending order using custom Comparator

Internally reverseOrder method calls a Comparator class to sort the list in reverse order. We can do it ourselves too by writing our own comparator class.

public class SortListDemo {
  public static void main(String[] args) {
    List<String> cityList = Arrays.asList("Delhi","Mumbai","Bangalore","Chennai","Kolkata","Mumbai");
     // sorting the list in descending order
    Collections.sort(cityList, (String a, String b)->  b.compareTo(a));
    System.out.println("List sorted in reverses order- " + cityList);
  }
}

Output

List sorted in reverses order- [Mumbai, Mumbai, Kolkata, Delhi, Chennai, Bangalore]

Note that Comparator is implemented as a lambda expression here.

Sorting Java ArrayList using sorted method of the Java Stream

public class SortListDemo {
  public static void main(String[] args) {
    List<String> cityList = Arrays.asList("Delhi","Mumbai","Bangalore","Chennai","Kolkata","Mumbai");
    List<String> tempList = cityList.stream().sorted().collect(Collectors.toList());
    System.out.println("List sorted in natural order- " + tempList);
    tempList = cityList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
    System.out.println("List sorted in reverse order- " + tempList);
  }
}

Output

List sorted in natural order- [Bangalore, Chennai, Delhi, Kolkata, Mumbai, Mumbai]
List sorted in reverse order- [Mumbai, Mumbai, Kolkata, Delhi, Chennai, Bangalore]

That's all for this topic How to Sort 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 Join Lists in Java
  3. How to Remove Duplicate Elements From an ArrayList in Java
  4. Difference Between Comparable and Comparator in Java
  5. Java Collections Interview Questions And Answers

You may also like-

  1. Fail-Fast Vs Fail-Safe Iterator in Java
  2. How to Iterate a HashMap of ArrayLists of String in Java
  3. static import in Java
  4. Interface Static Methods in Java
  5. Method Reference in Java
  6. Count Number of Times Each Character Appears in a String Java Program
  7. Java ThreadLocal Class With Examples
  8. Try-With-Resources in Java With Examples

RunnableBranch in LangChain With Examples

RunnableBranch in LangChain conditionally branches to one of the Runnable chains based on the user input. RunnableBranch acts like an if-elif-else structure routing input to different chains based on a specified condition.

How RunnableBranch Works

You can pass a list of (condition, Runnable) pairs to the RunnableBranch class to create a conditional routing runnable that evaluates each condition in sequence and executes the corresponding chain, falling back to the default runnable if none of the conditions match. For example-

RunnableBranch(
    (lambda x: route_query(x["query"]) == "support", support_chain),
    (lambda x: route_query(x["query"]) == "sales", sales_chain),
    general_chain
)

LangChain RunnableBranch Example

This is the same example which was used in the RunnableLambda in LangChain With Examples post, covering the scenario where different specialized bots are used to handle different types of queries. A RunnableBranch ensures branching out to the support agent or sales agent based on the condition, with a "General" fallback for anything else.

Example Code

from langchain_core.prompts import PromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_ollama import ChatOllama
from langchain_core.runnables import RunnableBranch

support_template = "You are a support agent. User input: {query}. Provide 3 reasons for the issue."
sales_template = "You are a sales specialist. User input: {query}. Provide 3 reasons to buy the product and 3 for not buying."
general_template = "You are a general assistant. User input: {query}. Provide a helpful response."

model = ChatOllama(model="llama3.1", temperature=0.5)
# 1. Define specialized chains
support_chain = ChatPromptTemplate.from_template(support_template) | model | StrOutputParser()
sales_chain = ChatPromptTemplate.from_template(sales_template) | model | StrOutputParser()
general_chain = ChatPromptTemplate.from_template(general_template) | model | StrOutputParser()

# 2. Define routing logic 
def route_query(input: str) -> str:
    query = input.lower()
    print(f"Routing query: {query}")
    if "support" in query or "issue" in query:
        return "support"
    elif "price" in query or "buy" in query:
        return "sales"
    else:
        return "general"
    
branch = RunnableBranch(
    (lambda x: route_query(x["query"]) == "support", support_chain),
    (lambda x: route_query(x["query"]) == "sales", sales_chain),
    general_chain
)

# Example usage - Should go to support
response1 = branch.invoke({"query": "I have a login issue with my account."})
print(response1)

# Should go to sales
response2 = branch.invoke({"query": "Request to buy a 3D printer."})
print(response2)

# Should go to general chain
response3 = branch.invoke({"query": "Does company provide transportation services?"})
print(response3)

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


Related Topics

  1. What is LangChain - An Introduction
  2. LangChain PromptTemplate + Streamlit - Code Generator Example
  3. LangChain PromptTemplate + Streamlit - Code Generator Example
  4. Messages in LangChain
  5. RunnableParallel in LangChain With Examples

You may also like-

  1. String in Java Tutorial
  2. Array in Java
  3. Count Number of Words in a String Java Program
  4. Ternary Operator in Java With Examples
  5. Java Multithreading Interview Questions And Answers
  6. Java Exception Handling Tutorial
  7. ConcurrentHashMap in Java With Examples
  8. TreeMap in Java With Examples