Tuesday, March 17, 2026

Java Stream - concat() With Examples

The concat() method in the Java Stream API allows you to merge two streams into a single stream. It takes two streams as arguments and returns a new stream containing all elements of the first stream followed by all elements of the second. This makes it a convenient way to combine data sources while working with Java’s functional programming features.

Syntax of concat() method

concat(Stream<? extends T> a, Stream<? extends T> b)

Here parameters are-

  • a- the first stream
  • b- the second stream

Return Value: A new stream that represents the concatenation of both input streams.

Important Notes:

  • The resulting stream is ordered if both input streams are ordered.
  • It is parallel if either of the input streams is parallel.
  • Since streams in Java are consumed once, the concatenated stream should be used immediately to avoid losing data.

concat() method Java examples

1. Using concat() method to merge two streams of integers.

import java.util.stream.Stream;

public class StreamConcat {

  public static void main(String[] args) {
    Stream<Integer> stream1 = Stream.of(1, 2, 3);
      Stream<Integer> stream2 = Stream.of(4, 5, 6);
      Stream<Integer> mergedStream = Stream.concat(stream1, stream2);
      mergedStream.forEach(System.out::println);
  }
}

Output

1
2
3
4
5
6

2. Merging two Collections (Lists) by using concat() method of Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class StreamConcat {

  public static void main(String[] args) {
    List<String> strList1 = Arrays.asList("A","B","C","D");
    List<String> strList2 = Arrays.asList("E","F","G","H");
    // Getting streams using Lists as source
    Stream<String> stream1 = strList1.stream();
    Stream<String> stream2 = strList2.stream();
    
      Stream<String> mergedStream = Stream.concat(stream1, stream2);
      mergedStream.forEach(System.out::println);
  }
}

Output

A
B
C
D
E
F
G
H

3. You can also use concat() method along with other methods of the Java Stream, for example you can write a program to merge 2 lists while removing duplicates which can be done by using distinct() method.

public class StreamConcat {

  public static void main(String[] args) {
    List<String> strList1 = Arrays.asList("A","B","C","D");
    List<String> strList2 = Arrays.asList("E","B","G","A");
    // Getting streams using Lists as source
    Stream<String> stream1 = strList1.stream();
    Stream<String> stream2 = strList2.stream();
    
      Stream<String> mergedStream = Stream.concat(stream1, stream2).distinct();
      mergedStream.forEach(System.out::println);
  }
}

Output

A
B
C
D
E
G

4. Using concat() to merge multiple streams. You can also merge more than two streams by nesting the concat method.

public class StreamConcat {

  public static void main(String[] args) {
      Stream<Integer> stream1 = Stream.of(1, 2);
      Stream<Integer> stream2 = Stream.of(3, 4, 5);
      Stream<Integer> stream3 = Stream.of(7, 8, 9);
      Stream<Integer> stream4 = Stream.of(10, 11);
      Stream<Integer> mergedStream = Stream.concat(stream1, 
              Stream.concat(Stream.concat(stream2, stream3), stream4));
      mergedStream.forEach(e -> System.out.print(e + " "));
  }
}

Output

1 2 3 4 5 7 8 9 10 11 

That's all for this topic Java Stream - concat() 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. Java Stream - count() With Examples
  2. Java Stream - boxed() With Examples
  3. Java Stream - findFirst() With Examples
  4. Java Stream - sorted() With Examples
  5. Java Stream - skip() With Examples

You may also like-

  1. Reflection in Java - Getting Class Information
  2. Java do-while Loop With Examples
  3. strictfp in Java
  4. Count Number of Times Each Character Appears in a String Java Program
  5. Stack Implementation in Java Using Linked List
  6. Class And Object in Python
  7. Spring WebFlux Example Using Functional Programming - Spring Web Reactive
  8. Highlight Currently Selected Menu Item Angular Routing Example

How to Convert float to int in Java

When working with numbers in Java, you may often need to display values without decimal points. In such cases, converting a float to an int becomes essential. This guide will walk you through how to convert float to int in Java, explaining the different approaches and their implications.

While performing this conversion, two main concerns arise:

  • Range limitations: A float can represent a much larger range than an int. If the float value exceeds the int range, you need to understand how Java handles overflow
  • Rounding behavior: Converting a float with decimal places to an int will truncate the fractional part. Knowing whether you want truncation, rounding, or another strategy is crucial for accurate results.

In the sections below, we’ll explore the available options for converting float to int in Java, demonstrate code examples, and explain how these concerns are addressed in Java.


1. Using Float.intValue() method

You can use the intValue() method of the Float wrapper class to convert float to int. Description of the intValue() method is as following.

  • intValue()- Returns the value of this Float as an int after a narrowing primitive conversion.
public class FloatToInt {
 public static void main(String[] args) {
  Float f = new Float(567.678);
  int val = f.intValue();
  System.out.println("int value " + val);
 }
}

Output

int value 567

Here you can see that rounding doesn’t happen while converting, just the digits after the decimal points are removed. You will get the same result if you use type casting instead.

2. Conversion from float to int Using typecasting

public class FloatToInt {
 public static void main(String[] args) {
  float fVal = 567.678f;
  // type casting
  int val1 = (int)fVal;
  System.out.println("int value " + val1);
 }
}

Output

int value 567

Here again you can see by type casting digits after the decimal are removed and there is no rounding. The only difference between using Float.intValue() and explicit casting is you need Float object for using intValue() where as typecasting can be done with a primitive float data type.

3. Using Math.round() method

As you have seen above methods of converting float to int are just giving the whole part of the number but mostly you will also like to do rounding. For that you can use Math.round method which takes float as argument and returns the value of the argument rounded to the nearest int value.

There are also some special cases–

  • If the argument is NaN, the result is 0.
  • If the argument is negative infinity or any value less than or equal to the value of Integer.MIN_VALUE, the result is equal to the value of Integer.MIN_VALUE.
  • If the argument is positive infinity or any value greater than or equal to the value of Integer.MAX_VALUE, the result is equal to the value of Integer.MAX_VALUE.

Conversion from float to int - Math.round() example

If we take the same float value as used above

public class FloatToInt {

 public static void main(String[] args) {  
  float fVal = 567.678f;
  int rVal = Math.round(fVal);
  System.out.println("int value " + rVal);
 }
}

Output

int value 568

Here you can see that the value is rounded to the nearest int value.

Example with Some more values-

public class FloatToInt {
 public static void main(String[] args) {
  float f1 = -10.78f;
  float f2 = 4.4999f;
  float f3 = 105.12f;
  int i1 = Math.round(f1);
  int i2 = Math.round(f2);
  int i3 = Math.round(f3);
  System.out.println("float value: " + f1 + "int value: " + i1);
  System.out.println("float value: " + f2 + "int value: " + i2);
  System.out.println("float value: " + f3 + "int value: " + i3);
 }
}

Output

float value: -10.78int value: -11
float value: 4.4999int value: 4
float value: 105.12int value: 105

If float value out of range

If float value that has to be converted to int is out of range then the following rules are applied-

  • If the argument is negative infinity or any value less than or equal to the value of Integer.MIN_VALUE, the result is equal to the value of Integer.MIN_VALUE.
  • If the argument is positive infinity or any value greater than or equal to the value of Integer.MAX_VALUE, the result is equal to the value of Integer.MAX_VALUE.
public class FloatToInt {
 public static void main(String[] args) {
  Float f = new Float(567678865544.678);
  int val = f.intValue();
  System.out.println("int value " + val);
  
  float fVal = 567678865544.678f;
  int val1 = (int)fVal;
  System.out.println("int value " + val1); 
 }
}

Output

int value 2147483647
int value 2147483647

Here it can be seen that integer value is equal to Integer.MAX_VALUE as float value is greater than Integer.MAX_VALUE

Same way you can check for minimum value.

That's all for this topic How to convert float to int 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. Convert String to int in Java
  2. Convert double to int in Java
  3. How to Convert String to Date in Java
  4. Factorial Program in Java
  5. Arrange Non-Negative Integers to Form Largest Number - Java Program

You may also like-

  1. Java Program to Find First Non-Repeated Character in a Given String
  2. How to Find Common Elements Between Two Arrays Java Program
  3. Java Program to Get All DB Schemas
  4. Spring NamedParameterJdbcTemplate Select Query Example
  5. final Vs finally Vs finalize in Java
  6. Encapsulation in Java
  7. Constructor Overloading in Java
  8. Java Collections Interview Questions And Answers

Python String split() Method

In Python, the split() method is one of the most commonly used string operations. It allows you to break a string into a list of substrings based on a specified delimiter. If no delimiter is provided, the method defaults to splitting on whitespace, treating consecutive spaces as a single separator. This makes the Python String split() Method especially useful for parsing text data.

split() method syntax

str.split(separator, maxsplit)

Both of the parameters are optional.

separator- The delimiter on which the string will be split. If not specified, whitespace is used by default.

maxsplit- Defines the maximum number of splits. If omitted or set to -1, there is no limit.

Python also provides rsplit() method, which works like split() but performs splits starting from the right when maxsplit is specified.

Python split() method examples

1. Using the split method with default parameters (not passing any parameter explicitly).

s = "This is a    test   String"
#break String on spaces
list = s.split()
print(list)

Output

['This', 'is', 'a', 'test', 'String']

Since no parameter is passed with split() method so whitespace is used as separator. Note that consecutive whitespaces are regarded as a single separator when default is used.

2. Splitting on custom delimiters like comma (,) or pipe symbol (|).

s = "Chicago,Los Angeles,Seattle,Austin"
#break String on ,
list = s.split(',')
print(list)

s = "Chicago|Los Angeles|Seattle|Austin"
#break String on |
list = s.split('|')
print(list)

Output

['Chicago', 'Los Angeles', 'Seattle', 'Austin']
['Chicago', 'Los Angeles', 'Seattle', 'Austin']

3. Split string on backslash (\) symbol. With backslash it is better to use escape sequence (\\).

s = "c:\\users\\netjs\\python"
#break String on ,
list = s.split('\\')
print(list)

Output

['c:', 'users', 'netjs', 'python']

4. Limiting the splits using maxsplit parameter. Here split is done for max 2 items.

s = "Chicago|Los Angeles|Seattle|Austin"
#break String on |
list = s.split('|', 2)
print(list)

Output

['Chicago', 'Los Angeles', 'Seattle|Austin']

5. Using rsplit() method.

s = "Chicago|Los Angeles|Seattle|Austin"
#break String on |
list = s.rsplit('|', 2)
print(list)

Output

['Chicago|Los Angeles', 'Seattle', 'Austin']

6. Parsing CSV data with Python string split() method

One of the most practical applications of the Python String split() Method is parsing CSV (Comma-Separated Values) data. CSV files are widely used for storing tabular data such as user records, product catalogs etc. While Python provides a built-in csv module for robust handling, the split() method offers a quick and lightweight way to process simple CSV strings.

data = "Name,Age,Location"
row = "Ram,30,New Delhi"

# Split header and row using comma as delimiter
headers = data.split(',')
values = row.split(',')

# Combine into dictionary for easy access
record = dict(zip(headers, values))
print(record)

Output

{'Name': 'Ram', 'Age': '30', 'Location': 'New Delhi'}

That's all for this topic Python String split() Method. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Changing String Case in Python
  2. Python count() method - Counting Substrings
  3. Python Program to Reverse a String
  4. Operator Overloading in Python
  5. Abstract Class in Python

You may also like-

  1. Magic Methods in Python With Examples
  2. self in Python
  3. Namespace And Variable Scope in Python
  4. raise Statement in Python Exception Handling
  5. PermGen Space Removal in Java 8
  6. String join() Method And StringJoiner Class in Java
  7. Spring Web MVC Java Configuration Example
  8. Data Compression in Hadoop

Monday, March 16, 2026

Java StampedLock With Examples

Introduced in Java 8, the StampedLock in Java is a powerful concurrency utility designed to improve performance in multi-threaded applications. Unlike the traditional ReentrantReadWriteLock in Java, the StampedLock not only provides distinct read and write locks, but also supports optimistic locking for read operations, allowing threads to read data without blocking, as long as no write occurs concurrently.

Another key advantage of StampedLock in Java is its ability to upgrade a read lock to a write lock, a feature missing in ReentrantReadWriteLock. This makes it especially useful in scenarios where a read operation may need to transition into a write operation seamlessly.

Every locking method in StampedLock returns a stamp (a long value) that uniquely identifies the lock state. These stamps are then used to release locks, validate lock states, or convert between lock modes.

Here’s a simple example of acquiring and releasing a write lock using StampedLock in Java-

StampedLock sl = new StampedLock();
//acquiring writelock
long stamp =  sl.writeLock();
try{
 ...
 ...
}finally {
 //releasing lock
 sl.unlockWrite(stamp);
}

String Length in Python - len() Function

The len() function in Python is the simplest and most efficient way to determine the length of a string, list, tuple, dictionary, or any other iterable. When applied to a string, the len() function returns the total number of characters, including spaces and special symbols.

Syntax of len() function

len(object)

object can be a string, list, tuple, dictionary, or any iterable.

The function returns an integer representing the number of items or characters (in case of string) contained in the object.

String length using len() in Python

str = "netjs"
print(len(str))

str = "Hello World!"
strLen = len(str)
print('length of String- ',strLen)

Output

5
length of String-  12

That's all for this topic String Length in Python - len() Function. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. String Slicing in Python
  2. Python String split() Method
  3. Python Program to Check if Strings Anagram or Not
  4. Class And Object in Python
  5. Inheritance in Python

You may also like-

  1. Magic Methods in Python With Examples
  2. Namespace And Variable Scope in Python
  3. List in Python With Examples
  4. Tuple in Python With Examples
  5. Access Modifiers in Java
  6. How to Convert Date And Time Between Different Time-Zones in Java
  7. Spring Component Scan Example
  8. Installing Hadoop on a Single Node Cluster in Pseudo-Distributed Mode

Sunday, March 15, 2026

Python String join() Method

When working with text in Python, you’ll often need to combine multiple strings into one. The Python String join() method is the most efficient way to achieve this. It takes an iterable (like a list, tuple, set, dictionary, or even another string) and concatenates all its elements into a single string, inserting a specified separator between them

join() method syntax

str.join(iterable)

Here iterable is an object which can return its element one at a time like list, tuple, set, dictionary, string.

str represents a separator that is used between the elements of iterable while joining them.

All the values in iterable should be String, a TypeError will be raised if there are any non-string values in iterable.

Python join() method examples

1. join method with a tuple.

cities = ('Chicago','Los Angeles','Seattle','Austin')
separator = ':'
city_str = separator.join(cities)
print(city_str)

Output

Chicago:Los Angeles:Seattle:Austin

2. Python join() method with a list of strings.

cities = ['Chicago','Los Angeles','Seattle','Austin']
separator = '|'
city_str = separator.join(cities)
print(city_str)

Output

Chicago|Los Angeles|Seattle|Austin

3. TypeError if non-string instance is found.

cities = ['Chicago','Los Angeles','Seattle','Austin', 3]
separator = '|'
city_str = separator.join(cities)
print(city_str)

Output

    city_str = separator.join(cities)
TypeError: sequence item 4: expected str instance, int found

In the list there is an int value too apart from strings therefore TypeError is raised while attempting to join the elements of the list.

4. Python join() method with a Set. Since set is an unordered collection so sequence of elements may differ.

cities = {'Chicago','Los Angeles','Seattle','Austin'}
separator = '-'
city_str = separator.join(cities)
print(city_str)

Output

Austin-Los Angeles-Chicago-Seattle

5. join() method with a Dictionary. In case of dictionary keys are joined not the values.

cities = {'1':'Chicago','2':'Los Angeles','3':'Seattle','4':'Austin'}
separator = '-'
city_str = separator.join(cities)
print(city_str)

Output

1-2-3-4

That's all for this topic Python String join() Method. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python String split() Method
  2. Check if String Present in Another String in Python
  3. pass Statement in Python
  4. Namespace And Variable Scope in Python
  5. Interface in Python

You may also like-

  1. Python Installation on Windows
  2. Class And Object in Python
  3. Keyword Arguments in Python
  4. Bubble Sort Program in Python
  5. JVM Run-Time Data Areas - Java Memory Allocation
  6. final Keyword in Java With Examples
  7. BeanPostProcessor in Spring Framework
  8. How to Write a Map Only Job in Hadoop MapReduce

Check if String Present in Another String in Python

When working with text, you’ll often need to check if a string is present in another string in Python. Thankfully, Python provides multiple simple and efficient ways to perform this task:

  • Use Python membership operators 'in' and 'not in'. This is the most Pythonic way to check substring existence. See example.
  • Using find() method to check if string contains another string. See example.
  • Using index() method to get the index of the substring with in the String. See example.

Python membership operators - in and not in

To check if a string exists inside another string in Python or not, you can use 'in' and 'not in' membership operators.

  • 'in' operator- Returns true if the string is part of another string otherwise false.
  • 'not in' operator- Returns true if the string is not part of another string otherwise false.

Python in operator example

def check_membesrship(str1, str2):
  if str2 in str1:
    print(str2, 'found in String')
  else:
    print(str2, 'not found in String')

str1 = "This is Python"
str2 = "Python"
check_membesrship(str1, str2)
#another call
check_membesrship(str1, 'That')

Output

Python found in String
That not found in String

Python not in operator example

def check_membesrship(str1, str2):
  if str2 not in str1:
    print(str2, 'not found in String')
  else:
    print(str2, 'found in String')

str1 = "This is Python"
str2 = "Python"
check_membesrship(str1, 'That')
#another call
check_membesrship(str1, str2)

Output

That not found in String
Python found in String

Using find() method to check if substring exists in string

Using find() method in Python you can check if substring is part of the string or not. If found, this method returns the index of the first occurrence of the substring otherwise -1 is returned.

Python find() method example

def check_membesrship(str, substr):
  loc = str.find(substr)
  if loc == -1:
    print(substr, 'not found in String')
  else:
    print(substr, 'found in String at index', loc)


str1 = "This is Python"
str2 = "Python"
check_membesrship(str1, str2)
#another call
check_membesrship(str1, 'That')

Output

Python found in String at index 8
That not found in String

Using index() method to check if substring exists in string

Using index() method in Python you can check if substring is part of the string or not. This method is similar to find() and returns the location of the first occurrence of the substring if found. If not found then index() method raises ‘ValueError’ exception that's where it differs from find().

Python index() method example

def check_membesrship(str, substr):
  # Catch ValueError exception
  try:
    loc = str.index(substr)
  except ValueError:
    print(substr, 'not found in String')
  else:
    print(substr, 'found in String at index', loc)


str1 = "This is Python"
str2 = "Python"
check_membesrship(str1, str2)
#another call
check_membesrship(str1, 'That')

Output

Python found in String at index 8
That not found in String

That's all for this topic Check if String Present in Another String 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. String Slicing in Python
  2. Accessing Characters in Python String
  3. Python String join() Method
  4. Magic Methods in Python With Examples
  5. Nonlocal Keyword in Python With Examples

You may also like-

  1. Name Mangling in Python
  2. Operator Overloading in Python
  3. Passing Object of The Class as Parameter in Python
  4. Difference Between Function and Method in Python
  5. instanceof Operator in Java
  6. Java Exception Handling Tutorial
  7. Checking Number Prime or Not Java Program
  8. Spring Setter Based Dependency Injection