
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert Integer to String Using Map in Java
In this article, we will learn to convert integers to String with Map in Java. The Stream API has become an essential tool for processing collections of data in a more declarative and readable way. Instead of using traditional loops, streams allow developers to filter, map, and perform other operations on data with minimal code
Problem Statement
Given an integer, we need to convert it to its string representation where the integer is treated as a character (e.g., 5 becomes "5", 10 becomes "10"). We'll use a Map to define the integer-to-string mappings and retrieve the string equivalent for a given integer.
Input
5
Output
"5"
Converting integers to String with Map
We need to filter out the integers that are greater than 400 and then transform each of these values into a formatted string that includes a descriptive message. Finally, we need to print each of these formatted strings to the console.
Following is the step-by-step process to convert integers to strings using map ?
Creating a List of Values
The Arrays.asList() method creates a list of integers ?
Arrays.asList(20, 50, 100, 200, 250, 300, 500, 550, 600, 700)
Filtering Values
The filter() operation includes only the values greater than 400. This is done using a lambda expression ?
.filter(val -> val > 400)
Generating a Stream
The stream() method converts the list into a stream ?
.stream()
Mapping Values
The map() method transforms each value in the stream into a formatted string ?
.map(val -> "Value greater than 400 = " + String.valueOf(val))
Printing Results
The forEach terminal operation iterates over each element in the stream and prints it to the console ?
.forEach(val -> System.out.println(val));
Example
The following is an example of converting an integer to a string with a map ?
import java.util.Arrays; public class Demo { public static void main(String[] args) { Arrays.asList(20, 50, 100, 200, 250, 300, 500, 550, 600, 700) .stream() .filter(val -> val > 400) .map(val -> "Value greater than 400 = " + String.valueOf(val)) .forEach(val -> System.out.println(val)); } }
Output
Value greater than 400 = 500 Value greater than 400 = 550 Value greater than 400 = 600 Value greater than 400 = 700
Time Complexity: The overall time complexity is O(n), where n is the number of elements in the input list.
Space Complexity: The space complexity is O(n) due to the space required for storing the input list and the intermediate results during processing.