The Programmer's Guide
  • About
  • Algorithm
    • Big O Notation
      • Tree
      • Problems
    • Basic Notes
    • Data Structure Implementation
      • Custom LinkedList
      • Custom Stack
      • Custom Queue
      • Custom Tree
        • Binary Tree Implementation
        • Binary Search Tree Implementation
        • Min Heap Implementation
        • Max Heap Implementation
        • Trie Implementation
      • Custom Graph
        • Adjacency List
        • Adjacency Matrix
        • Edge List
        • Bidirectional Search
    • Mathematical Algorithms
      • Problems - Set 1
      • Problems - Set 2
    • Bit Manipulation
      • Representation
      • Truth Tables
      • Number System
        • Java Program
      • Problems - Set 1
    • Searching
    • Sorting
    • Array Algorithms
    • String Algorithms
    • Tree
      • Tree Traversal Techniques
      • Tree Implementation
      • Applications of Trees
      • Problems - Set 1
    • Graph
      • Graph Traversal Techniques
      • Shortest Path Algorithms
      • Minimum Spanning Tree (MST) Algorithms
    • Dynamic Programming
      • Problems - Set 1
    • Recursion
    • Parallel Programming
    • Miscellaneous
      • Problems - Set 1
  • API
    • API Basics
      • What is an API?
      • Types of API
        • Comparison - TBU
      • Synchronous vs Asynchronous API
    • API Architecture
      • Synchronous & Asynchronous Communication
    • API Specification
  • Cloud Computing
    • Cloud Fundamentals
      • Cloud Terminology
      • Core Terminology
      • Cloud Models
      • Cloud Service Models
      • Benefits, Challenges and Risk of Cloud Computing
      • Cloud Ecosystem
  • Database
    • DBMS
      • Types of DBMS
        • Relational DBMS (RDBMS)
        • NoSQL DBMS
        • Object-Oriented DBMS (OODBMS)
        • Columnar DBMS
        • In-Memory DBMS
        • Distributed DBMS
        • Cloud-Based DBMS
        • Hierarchical DBMS
      • DBMS Architecture
      • DBMS Structure
    • SQL Databases
      • Terminology
      • RDBMS Concepts
        • Entity Relationship Diagram (ERD)
          • ERD Examples
        • Normalization
        • Denormalization
        • ACID & BASE Properties
          • ACID Properties
          • BASE Properties
        • Locking and Unlocking
      • SQL Fundamentals
        • SQL Commands
          • DDL (Data Definition Language)
          • DML (Data Manipulation Language)
          • DCL (Data Control Language)
          • TCL (Transaction Control Language)
          • DQL (Data Query Language)
        • SQL Operators
          • INTERSECT
          • EXCEPT
          • MINUS
          • IN and NOT IN
          • EXISTS and NOT EXISTS
        • SQL Clauses
          • Joins
          • OVER
          • WITH
          • CONNECT BY
          • MODEL
          • FETCH FIRST
          • KEEP
          • OFFSET with FETCH
        • SQL Functions
          • Oracle Specific
        • SQL Data Types
          • Numeric Types
          • Character Types
          • Date & Time Types
          • Large Object Types
        • Others
          • Indexing
      • Vendor Specific Concepts
        • Oracle Specific
          • Data Types
          • Character Set
          • Rownum, Rowid, Urowid
          • Order of Execution of the query
          • Keys
          • Tablespace
          • Partition
      • Best Practice
      • Resources & References
        • O’Reilly SQL Cookbook (2nd Edition)
          • 1. Retrieving Records
          • 2. Sorting Query Results
          • 3. Working with Multiple Tables
          • 4. Inserting, Updating, and Deleting
          • 5. Metadata Queries
          • 6. Working with Strings
          • 7. Working with Numbers
          • 8. Date Arithmetic
          • 9. Date Manipulation
          • 10. Working with Ranges
          • 11. Advanced Searching
          • 12. Reporting and Reshaping
          • 13. Hierarchical Queries
          • 14. Odds 'n' Ends
    • SQL vs NoSQL
    • Best Practices
  • Git
    • Commands
      • Setup and Configuration Commands
      • Getting and Creating Projects
      • Tracking Changes
      • Branching and Merging
      • Sharing and Updating Projects
      • Inspection and Comparison
      • Debugging
      • Patching
      • Stashing and Cleaning
      • Advanced Manipulations
    • Workflows
      • Branching Strategies
        • Git Flow
        • Trunk-Based Development
        • GitHub Flow
        • Comparison
      • Merge Strategies
        • Merge
        • Rebase
        • Squash
        • Fast-forward vs No-fast-forward
        • MR vs PR
      • Conflict Resolution
        • Handling Merge Conflicts
        • Merge Conflicts
        • Rebase Conflicts
        • Divergent Branches After git pull
        • Force Push
      • Patch & Recovery
        • Cherry-pick strategies
        • Revert vs Reset
        • Recover from a bad rebase
      • Rebasing Practices
        • Merge vs Rebase
        • Rebase develop branch on main branch
      • Repository Management
        • Working Directory
        • Mirror a repository
        • Convert a local folder to a Git repo
        • Backup and restore a Git repository
  • Java
    • Java Installation
    • Java Distributions
    • Java Platform Editions
      • Java SE
      • Java EE
      • Jakarta EE
      • Java ME
      • JavaFX
    • Java Overview
      • OOP Principles
        • Encapsulation
        • Inheritance
        • Polymorphism
        • Abstraction
          • Abstract Class & Method
          • Interface
            • Functional Interfaces
            • Marker Interfaces
          • Abstract Class vs Interface
      • OOP Basics
        • What is a Class?
          • Types of Classes
        • What is an Object?
          • Equals and HashCode
            • FAQ
          • Shallow Copy and Deep Copy
          • Ways to Create Object
          • Serialization & Deserialization
        • Methods & Fields
          • Method Overriding & Overloading
          • Method Signature & Header
          • Variables
        • Constructors
        • Access Modifiers
      • Parallelism & Concurrency
        • Ways to Identify Thread Concurrency or Parallelism
        • Thread Basics
          • Thread vs Process
          • Creating Threads
          • Thread Context Switching
          • Thread Lifecycle & States
          • Runnable & Callable
          • Types of Threads
          • Thread Priority
        • Thread Management & Synchronisation
          • Thread Resource Sharing
          • Thread Synchronization
            • Why is Synchronization Needed?
            • Synchronized Blocks & Methods
          • Thread Lock
            • Types of Locks
            • Intrinsic Lock (Monitor Lock)
            • Reentrant Lock
          • Semaphore
          • Thread Starvation
          • Thread Contention
          • Thread Deadlock
          • Best Practices for Avoiding Thread Issues
      • Keywords
        • this
        • super
        • Access Modifiers
      • Data Types
        • Default Values
        • Primitive Types
          • byte
          • short
          • int
          • long
          • float
          • double
          • char
          • boolean
        • Non-Primitive (Reference) Types
          • String
            • StringBuilder
            • StringBuffer
              • Problems
            • Multiline String
            • Comparison - String, StringBuilder & StringBuffer
          • Array
          • Collections
            • List
              • Array vs List
              • ArrayList
              • Vector
                • Stack
                  • Problems
              • LinkedList
            • Queue
              • PriorityQueue
              • Deque (Double-Ended Queue)
                • ArrayDeque
                • ConcurrentLinkedDeque - TBU
                • LinkedBlockingDeque - TBU
            • Map
              • HashMap
              • Hashtable
              • LinkedHashMap
              • ConcurrentHashMap
              • TreeMap
              • EnumMap
              • WeakHashMap
            • Set
              • HashSet
              • LinkedHashSet
              • TreeSet
              • EnumSet
              • ConcurrentSkipListSet
              • CopyOnWriteArraySet
        • Specialized Classes
          • BigInteger
          • BigDecimal
            • Examples
          • BitSet
          • Date and Time
            • Examples
          • Optional
          • Math
          • UUID
          • Scanner
          • Formatter
            • Examples
          • Properties
          • Regex (Pattern and Matcher)
            • Examples
          • Atomic Classes
          • Random
          • Format
            • NumberFormat
            • DateFormat
            • DecimalFormat
        • Others
          • Object
          • Enum
            • Pre-Defined Enum
            • Custom Enum
            • EnumSet and EnumMap
          • Record
          • Optional
          • System
          • Runtime
          • ProcessBuilder
          • Class
          • Void
          • Throwable
            • Error
            • Exception
              • Custom Exception Handling
              • Best Practice
            • Error vs Exception
            • StackTraceElement
    • Java Features by Version
      • How New Java Features are Released ?
      • Java Versions
        • Java 8
        • Java 9
        • Scoped Values
        • Unnamed Variables & Patterns
      • FAQ
    • Concepts
      • Set 1
        • Streams
          • flatmap
          • Collectors Utility Class
          • Problems
        • Functional Interfaces
          • Standard Built-In Interfaces
          • Custom Interfaces
        • Annotation
          • Custom Annotation
          • Meta Annotation
        • Generics
          • Covariance and Invariance
        • Asynchronous Computation
          • Future
          • CompletableFuture
          • Future v/s CompletableFuture
          • ExecutorService
            • Thread Pool
            • Types of Work Queues
            • Rejection Policies
            • ExecutorService Implementations
            • ExecutorService Usage
          • Locks, Atomic Variables, CountDownLatch, CyclicBarrier - TBU
          • Parallel Streams, Fork/Join Framework,Stream API with Parallelism - TBU
      • Set 2
        • Standards
          • ISO Standards
          • JSR
            • JSR 303, 349, 380 (Bean Validation)
        • Operator Precedence
      • Set 3
        • Date Time Formatter
        • Validation
      • Set 4
        • Input from User
        • Comparison & Ordering
          • Object Equality Check
          • Comparable and Comparator
            • Comparator Interface
          • Sorting of Objects
          • Insertion Ordering
    • Packages
      • Core Packages
        • java.lang
          • java.lang.System
          • java.lang.Thread
      • Jakarta Packages
        • jakarta.validation
        • javax.validation
      • Third-party Packages
    • Code Troubleshoot
      • Thread Dump
      • Heap Dump
    • Code Quality & Analysis
      • ArchUnit
      • Terminologies
        • Cyclic dependencies
    • Code Style
      • Naming Convention
      • Package Structure
      • Formatting
      • Comments and Documentation
      • Imports
      • Exception Handling
      • Class Structure
      • Method Guidelines
      • Page 1
      • Code Smells to Avoid
      • Lambdas and Streams Style
      • Tools
    • Tools
      • IntelliJ IDEA
        • Shortcuts for MAC
      • Apache JMeter
        • Examples
      • Thread Dump Capture
        • jstack
        • VisualVM - TBU
        • jcmd - TBU
        • JConsole - TBU
        • YourKit Java Profiler - TBU
        • Eclipse MAT - TBU
        • IntelliJ IDEA Profiler - TBU
        • AppDynamics - TBU
        • Dynatrace - TBU
        • Thread Dump Analyzers - TBU
      • Heap Dump Capture
        • jmap
        • VisualVM - TBU
        • jcmd - TBU
        • Eclipse MAT (Memory Analyzer Tool) - TBU
        • IntelliJ IDEA Profiler - TBU
        • YourKit Java Profiler - TBU
        • AppDynamics - TBU
        • Dynatrace - TBU
        • Kill -3 Command - TBU
        • jhat (Java Heap Analysis Tool) - TBU
        • JVM Options - TBU
      • Wireshark
        • Search Filters
    • Best Practices
      • Artifact and BOM Versioning
  • Maven
    • Installation
    • Local Repository & Configuration
    • Command-line Options
    • Build & Lifecycle
    • Dependency Management
      • Dependency
        • Transitive Dependency
        • Optional Dependency
      • Dependency Scope
        • Maven Lifecycle and Dependency Scope
      • Dependency Exclusions & Overrides
      • Bill of Materials (BOM)
      • Dependency Conflict Resolution
      • Dependency Tree & Analysis
      • Dependency Versioning Strategies
    • Plugins
      • Build Lifecycle Management
      • Dependency Management
      • Code Quality and Analysis
      • Documentation Generation
      • Code Generation
      • Packaging and Deployment
      • Reporting
      • Integration and Testing
      • Customization and Enhancement
        • build-helper-maven-plugin
        • properties-maven-plugin
        • ant-run plugin
        • exec-maven-plugin
        • gmavenplus-plugin
      • Performance Optimization
    • FAQs
      • Fixing Maven SSL Issues: Unable to Find Valid Certification Path
  • Spring
    • Spring Basics
      • What is Spring?
      • Why Use Spring
      • Spring Ecosystem
      • Versioning
      • Setting Up a Spring Project
    • Core Concepts
      • Spring Core
        • Dependency Injection (DI)
        • Stereotype Annotation
      • Spring Beans
        • Bean Lifecycle
        • Bean Scope
          • Singleton Bean
        • Lazy & Eager Initialization
          • Use Case of Lazy Initialization
        • BeanFactory
        • ApplicationContext
      • Spring Annotations
        • Spring Boot Specific
        • Controller Layer (Web & REST Controllers)
    • Spring Features
      • Auto Configuration
        • Spring Boot 2: spring.factories
        • Spring Boot 3: spring.factories
      • Spring Caching
        • In-Memory Caching
      • Spring AOP
        • Before Advice
        • After Returning Advice
        • After Throwing Advice
        • After (finally) Advice
        • Around Advice
      • Spring File Handling
      • Reactive Programming
        • Reactive System
        • Reactive Stream Specification
        • Project Reactor
          • Mono & Flux
      • Asynchronous Computation
        • @Async annotation
      • Spring Security
        • Authentication
          • Core Components
            • Security Filter Chain
              • HttpSecurity
              • Example
            • AuthenticationManager
            • AuthenticationProvider
            • UserDetailsService
              • UserDetails
              • PasswordEncoder
            • SecurityContext
            • SecurityContextHolder
            • GrantedAuthority
            • Security Configuration (Spring Security DSL)
          • Authentication Models
            • One-Way Authentication
            • Mutual Authentication
          • Authentication Mechanism
            • Basic Authentication
            • Form-Based Authentication
            • Token-Based Authentication (JWT)
            • OAuth2 Authentication
            • Multi-Factor Authentication (MFA)
            • SAML Authentication
            • X.509 Certificate Authentication
            • API Key Authentication
            • Remember-Me Authentication
            • Custom Authentication
          • Logout Handling
        • Authorization
        • Security Filters and Interceptors
        • CSRF
          • Real-World CSRF Attacks & Prevention
        • CORS
        • Session Management and Security
        • Best Practices
      • Spring Persistence
        • JDBC
          • JDBC Components
          • JDBC Template
          • Transaction Management
          • Best Practices in JDBC Usage
          • Datasource
            • Connection Pooling
              • HikariCP
            • Caching
        • JPA (Java Persistence API)
          • JPA Fundamentals
          • ORM Mapping Annotations
            • 1. Entity and Table Mappings
            • 2. Field/Column Mappings
            • 3. Relationship Mappings
            • 4. Inheritance Mappings
            • 5. Additional Configuration Annotations
          • Querying Data
            • JPQL
            • Criteria API
            • JPA Specification
              • Example - Employee Portal
            • Native SQL Queries
            • Named Queries
            • Query Return Types
            • Pagination & Sorting
              • Example - Employee Portal
            • Projection
          • Fetch Strategies in JPA
        • JPA Implementation
          • Hibernate
            • Properties
            • Example
        • Spring Data JPA
          • Repository Abstractions
          • Entity-to-Table Mapping
          • Derived Query Methods
        • Cross-Cutting Concerns
          • Transactions
          • Caching
          • Concurrency
        • Examples
          • Employee Portal
            • API
    • Distributed Systems & Communication
      • Distributed Scheduling
      • Inter-Service Communication
        • 1. RestTemplate
        • 2. WebClient
        • 3. OpenFeign
        • Retry Mechanism
          • @Retryable annotation
            • Example
    • Security & Data Protection
      • Encoding | Decoding
        • Types
          • Base Encoding
            • Base16 - TBD
              • Encoding and Decoding in Java - TBD
            • Base32
              • Encoding and Decoding in Java
            • Base64 -TBD
              • Encoding and Decoding in Java - TBD
          • Text Encoding - TBD
            • Extended ASCII
              • Encoding and Decoding in Java - TBD
                • ISO-8859-1
                • Windows-1252 - TBD
                • IBM Code Pages - TBD
            • ASCII
              • Encoding and Decoding in Java
        • Java Guidelines
          • Text Encoding Decoding Examples
          • Base Encoding Decoding Examples
          • Best Practices and Concepts
          • Libraries
      • Cryptography
        • Terminology
        • Java Cryptography Architecture (JCA)
        • Key Management
          • Key Generation
            • Tools and Libraries
              • OpenSSL
              • Java Keytool
                • Concept
                • Use Cases
            • Key & Certificate File Formats
          • Key Distribution
          • Key Storage
          • Key Rotation
          • Key Revocation
        • Encryption & Decryption
          • Symmetric Encryption
            • Algorithm
            • Modes of Operation
            • Examples
          • Asymmetric Encryption
            • Algorithm
            • Mode of Operation
            • Examples
    • Utilities & Libraries
      • Apache Libraries
        • Apache Camel
          • Camel Architecture
            • Camel Context
            • Camel Endpoints
            • Camel Components
            • Camel Exchange & MEP
          • Spring Dependency
          • Different Components
            • Camel SFTP
        • Apache Commons Lang
      • MapStruct Mapper
      • Utilities by Spring framework
        • FileCopyUtils
    • General Concepts
      • Spring Boot Artifact Packaging
      • Classpath and Resource Loading
      • Configuration - Mapping Properties to Java Class
      • Validations in Spring Framework
        • Jakarta Validation
          • Jakarta Bean Validation Annotations
    • Practical Guidelines
      • Spring Configuration
      • Spring Code Design
  • Software Testing
    • Software Testing Methodologies
      • Functional Testing
      • Non Functional Testing
    • Software Testing Life Cycle (STLC)
    • Integration Test
      • Dynamic Property Registration
    • Java Test Framework
      • JUnit
        • JUnit 4
          • Examples
        • JUnit 5
          • Examples
        • JUnit 4 vs JUnit 5
  • System Design
    • Foundations
      • Programming Paradigms
      • Object-Oriented Design
        • SOLID Principles
        • GRASP Principles
        • Composition
        • Aggregation
        • Association
      • Design Pattern
        • Creational Pattern
        • Structural Pattern
        • Behavioral Pattern
        • Examples
          • Data Collector
          • Payment Processor
        • Design Enhancements
          • Fluent API Design
            • Examples
    • Architectural Building Blocks
      • CAP Theorem
      • Load Balancer
        • Load Balancer Architecture
        • Load Balancing in Java Microservices
          • Client-Side Load Balancing Example
          • Server-Side Load Balancing Example
        • Load Balancer Monitoring Tool
      • Scaling
        • Vertical Scaling (Scaling Up)
        • Horizontal Scaling (Scaling Out)
        • Auto-Scaling
        • Database Scaling via Sharding
      • Caching
        • Pod-Level vs Distributed Caching
      • Networking Metrics
        • Types of Delay
        • Scenario
      • System Characteristics
      • Workload Types
      • Resilience & Failure Handling
    • Performance
      • Why Is My API Sometimes Slow ?
    • Security
      • Security by Design
      • Zero Trust Security Model
      • Zero Trust Architecture
      • Principles
        • CIA
        • Least Privilege Principle
        • Defense in Depth
      • Security Threats & Mitigations
        • OWASP
          • Top 10 Security Threats
          • Application Security Verification Standard
          • Software Assurance Maturity Model
          • Dependency Check
          • CSRFGuard
          • Cheat Sheets
          • Security Testing Guide
          • Threat Dragon
        • Threat Modeling
      • Compliance & Regulation
        • PCI DSS
    • Deployment Patterns
    • Diagrams
      • UML Diagrams
        • PlantUML
          • Class Diagram
          • Object Diagram
          • Sequence Diagram
          • Use Case Diagram
          • Activity Diagram
          • State Diagram
          • Architecture Diagram
          • Component Diagram
          • Timing Diagram
          • ER Diagram (Entity-Relationship)
          • Network Diagram
    • Common Terminologies
    • Problems
      • Reference Materials
      • Cache Design
  • Interview Guide
    • Non-Technical
      • Behavioural or Introductory Guide
      • Project Specific
    • Technical
      • Java Interview Companion
        • Java Key Concepts
          • Set 1
          • Set 2
        • Java Code Snippets
        • Java Practice Programs
          • Set 3 - Strings
          • Set 4 - Search
          • Set 5 - Streams and Collection
      • SQL Interview Companion
        • SQL Practice Problems
          • Set 1
      • Spring Interview Companion
        • Spring Key Concepts
          • Set 1 - General
          • Set 2 - Core Spring
        • Spring Code Snippets
          • JPA
      • Application Server
      • Maven
      • Containerized Application
      • Microservices
    • General
      • Applicant Tracking System (ATS)
      • Flowchart - How to Solve Coding Problem?
Powered by GitBook
On this page
  • Basic Problems
  • Convert List to Uppercase
  • Filter Even Numbers
  • Count Strings Starting with ‘A’
  • Find Maximum Number
  • Find Minimum Number
  • Calculate Sum
  • Check if All Elements are Positive
  • Concatenate List of Strings
  • Sort a List
  • Remove Duplicates from List
  • Intermediate Problems
  • Find Second Highest Number
  • Group Strings by Length
  • Partition List into Even and Odd
  • Find First Non-Repeating Character
  • Convert List of Strings to Map
  • Find the Most Frequent Element
  • Find the First Three Elements
  • Find All Palindromes
  • Sort Employees by Salary
  • Convert List of Strings to a Single String
  • Advanced Problems
  • Find the Longest Word
  • Find the Average Salary of Employees
  • Group Employees by Department
  • Find the Oldest Employee in Each Department
  • Find Duplicate Elements in a List
  • Convert a List of Employees into a Map
  • Find the Youngest Employee
  • Find the Longest and Shortest Words in a Sentence
  • Find the Average Age of Employees by Department
  • Count the Occurrences of Each Character in a String
  • Flatten a List of Lists
  • Find Top 3 Highest Salaries
  • Convert a List of Objects to JSON String
  • Find All Employees Older Than 30 and Sort by Salary
  • Find the Median Salary
  • Sort a List of Employees by Multiple Criteria
  • Find the First N Prime Numbers
  • Calculate Factorial Using Streams
  • Check if a String is an Anagram of Another String
  • Find the Kth Largest Element in a List
  • Generate a Fibonacci Series Using Streams
  • Find the Most Expensive Product in Each Category
  • Find Most Common Words in a Paragraph
  • Merge Two Sorted Lists into One Sorted List
  • Check if a Sentence is a Pangram
  • Find the Sum of All Even-Indexed Elements in a List
  • Simulate a Voting System Using Streams

Was this helpful?

  1. Java
  2. Concepts
  3. Set 1
  4. Streams

Problems

Basic Problems

Convert List to Uppercase

Given a List<String>, convert all elements to uppercase.

List<String> strList = List.of("Apple", "banana", "Orange", "Avocado");
List<String> strListUpperCase = strList.stream().map(String::toUpperCase).toList();

Filter Even Numbers

Given a List<Integer>, filter out only even numbers.

List<Integer> intList = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> intListEven = intList.stream().filter(n -> n % 2 == 0).toList();

Count Strings Starting with ‘A’

Given a List<String>, count how many strings start with ‘A’.

List<String> strList = List.of("Apple", "banana", "Orange", "Avocado");
long strListStartsWithA = strList.stream().filter(str -> str.startsWith("A")).count();

Find Maximum Number

Find the maximum number in a List<Integer>.

List<Integer> numbers = Arrays.asList(3, 5, 7, 2, 8, 1);
Optional<Integer> max = numbers.stream().max(Integer::compare);
max.ifPresent(System.out::println);

Find Minimum Number

Find the minimum number in a List<Integer>.

List<Integer> numbers = Arrays.asList(3, 5, 7, 2, 8, 1);
Optional<Integer> min = numbers.stream().min(Integer::compare);
min.ifPresent(System.out::println);

Calculate Sum

Find the sum of all elements in a List<Integer>.

List<Integer> numbers = Arrays.asList(3, 5, 7, 2, 8, 1);
int sum = numbers.stream().mapToInt(Integer::intValue).sum();

Check if All Elements are Positive

Verify if all numbers in a List<Integer> are positive.

List<Integer> numbers = Arrays.asList(3, 5, 7, 2, 8, 1);
boolean allPositive = numbers.stream() .allMatch(n -> n > 0);
boolean isAllPositive = intList.stream().noneMatch(n -> n < 0);

Concatenate List of Strings

Join all strings in a List<String> using a comma.

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
String concatenated = names.stream().collect(Collectors.joining(", "));

Sort a List

Given a List<Integer>, sort it in ascending and descending order.

List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// Sort list in ascending order
List<Integer> sortedAscending = numbers.stream().sorted().collect(Collectors.toList());

// Sort list in descending order
List<Integer> sortedDescending = numbers.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());

Remove Duplicates from List

Remove duplicates from a List<String>.

List<String> strList = List.of("Apple", "banana", "Orange", "Avocado");
List<String> distinctString = strList.stream().distinct().toList();

Intermediate Problems

Find Second Highest Number

Find the second-highest number in a List<Integer>.

List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Optional<Integer> secondHighest = numbers.stream()
                                         .distinct()
                                         .sorted(Comparator.reverseOrder())
                                         .skip(1)
                                         .findFirst();

Group Strings by Length

Group a List<String> based on string length.

List<String> strList = List.of("Apple", "Banana", "Kiwi", "Orange", "tomato");
Map<Integer, List<String>> map = strList.stream().collect(Collectors.groupingBy(String::length));
// {4=[Kiwi], 5=[Apple], 6=[Banana, Orange, tomato]}

Partition List into Even and Odd

Partition a List<Integer> into even and odd numbers.

List<Integer> intList = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Map<Boolean, List<Integer>> map = intList.stream().collect(Collectors.partitioningBy(n -> n % 2 == 0));
// {false=[1, 3, 5, 7, 9], true=[2, 4, 6, 8, 10]}

Find First Non-Repeating Character

Find the first non-repeating character in a String.

String str = "swiss";

Optional<Character> firstNonRepeating = str.chars()
            .mapToObj(c -> (char) c)
            .collect(Collectors.groupingBy(c -> c, LinkedHashMap::new, Collectors.counting()))
            .entrySet().stream()
            .filter(entry -> entry.getValue() == 1)
            .map(Map.Entry::getKey)
            .findFirst();

System.out.println(firstNonRepeating.orElse(null));

Convert List of Strings to Map

Convert a List<String> into a Map<String, Integer> where the key is the string and the value is its length.

List<String> strList = List.of("Apple", "Banana", "Kiwi", "Orange", "tomato");
Map<String, Integer> map = strList.stream().collect(Collectors.toMap(str->str, String::length));
// {Apple=5, Kiwi=4, tomato=6, Orange=6, Banana=6}   

Find the Most Frequent Element

Find the most frequently occurring element in a List<Integer>.

List<Integer> numbers = Arrays.asList(1, 3, 2, 3, 4, 1, 3, 2, 1, 1, 4, 1);

Optional<Integer> mostFrequent = numbers.stream()
            .collect(Collectors.groupingBy(n -> n, Collectors.counting())) // Count occurrences
            .entrySet().stream()
            .max(Map.Entry.comparingByValue()) // Find entry with max count
            .map(Map.Entry::getKey);

System.out.println(mostFrequent.orElse(null)); // 1

Find the First Three Elements

Get the first three elements from a List<Integer>.

List<Integer> numbers = Arrays.asList(10, 20, 30, 40, 50);

List<Integer> firstThree = numbers.stream()
            .limit(3) // Take the first 3 elements
            .collect(Collectors.toList());

System.out.println(firstThree); // [10, 20, 30]

Find All Palindromes

Find all palindrome words in a List<String>.

List<String> words = Arrays.asList("madam", "apple", "racecar", "banana", "level", "hello");

List<String> palindromes = words.stream()
            .filter(word -> word.equalsIgnoreCase(new StringBuilder(word).reverse().toString())) // Check for palindrome
            .collect(Collectors.toList());

System.out.println(palindromes);

Sort Employees by Salary

Given a List<Employee>, sort employees by salary in descending order.

import java.util.*;
import java.util.stream.Collectors;

class Employee {
    private String name;
    private double salary;

    public Employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public double getSalary() {
        return salary;
    }

    @Override
    public String toString() {
        return name + " - $" + salary;
    }
}

public class SortEmployees {
    public static void main(String[] args) {
        List<Employee> employees = Arrays.asList(
            new Employee("Alice", 75000),
            new Employee("Bob", 50000),
            new Employee("Charlie", 90000),
            new Employee("David", 60000)
        );

        List<Employee> sortedEmployees = employees.stream()
            .sorted(Comparator.comparingDouble(Employee::getSalary).reversed()) // Sort by salary (descending)
            .collect(Collectors.toList());

        sortedEmployees.forEach(System.out::println);
    }
}
// Charlie - $90000.0
// Alice - $75000.0
// David - $60000.0
// Bob - $50000.0

Convert List of Strings to a Single String

Convert a List<String> into a single space-separated String.

List<String> words = Arrays.asList("Hello", "world", "Java", "Streams");

String result = words.stream()
        .collect(Collectors.joining(" ")); // Join with space
// Hello world Java Streams

Advanced Problems

Find the Longest Word

Find the longest word in a List<String>.

List<String> words = Arrays.asList("apple", "banana", "strawberry", "kiwi", "pineapple");

Optional<String> longestWord = words.stream()
            .max((s1, s2) -> Integer.compare(s1.length(), s2.length())); // Compare by length

longestWord.ifPresent(System.out::println); // strawberry

String longestWord2 = words.stream()
    .max(Comparator.comparingInt(String::length))
    .orElse(null);

Find the Average Salary of Employees

Given a List<Employee>, calculate the average salary.

class Employee {
    private String name;
    private double salary;

    public Employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }

    public double getSalary() {
        return salary;
    }
}

public class AverageSalary {
    public static void main(String[] args) {
        List<Employee> employees = Arrays.asList(
            new Employee("Alice", 50000),
            new Employee("Bob", 60000),
            new Employee("Charlie", 70000)
        );

        OptionalDouble avgSalary = employees.stream()
            .mapToDouble(Employee::getSalary) // Convert Employee to salary
            .average(); // Calculate average

        System.out.println(avgSalary.isPresent() ? avgSalary.getAsDouble() : "No employees found");
        // 60000.0
    }
}

Group Employees by Department

Group employees into a Map<String, List<Employee>> based on department.

import java.util.*;
import java.util.stream.Collectors;

class Employee {
    private String name;
    private int departmentId;

    public Employee(String name, int departmentId) {
        this.name = name;
        this.departmentId = departmentId;
    }

    public int getDepartmentId() {
        return departmentId;
    }

    @Override
    public String toString() {
        return name;
    }
}

public class GroupByDepartment {
    public static void main(String[] args) {
        List<Employee> employees = Arrays.asList(
            new Employee("Alice", 1),
            new Employee("Bob", 2),
            new Employee("Charlie", 1),
            new Employee("David", 3),
            new Employee("Eve", 2)
        );

        // Group employees by department ID
        Map<Integer, List<Employee>> employeesByDept = employees.stream()
            .collect(Collectors.groupingBy(Employee::getDepartmentId));

        // Print the grouped result
        employeesByDept.forEach((dept, empList) -> 
            System.out.println("Department " + dept + ": " + empList));
    }
}
// Department 1: [Alice, Charlie]
// Department 2: [Bob, Eve]
// Department 3: [David]

Find the Oldest Employee in Each Department

Find the oldest employee in each department.

import java.util.*;
import java.util.stream.Collectors;

class Employee {
    private String name;
    private int departmentId;
    private int age;

    public Employee(String name, int departmentId, int age) {
        this.name = name;
        this.departmentId = departmentId;
        this.age = age;
    }

    public int getDepartmentId() {
        return departmentId;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return name + " (Age: " + age + ")";
    }
}

public class OldestEmployeeInDepartment {
    public static void main(String[] args) {
        List<Employee> employees = Arrays.asList(
            new Employee("Alice", 1, 45),
            new Employee("Bob", 2, 30),
            new Employee("Charlie", 1, 50),
            new Employee("David", 3, 40),
            new Employee("Eve", 2, 35)
        );

        // Find the oldest employee in each department
        Map<Integer, Optional<Employee>> oldestByDept = employees.stream()
            .collect(Collectors.groupingBy(
                Employee::getDepartmentId, 
                Collectors.maxBy(Comparator.comparingInt(Employee::getAge))
            ));

        // Print the result
        oldestByDept.forEach((dept, emp) -> 
            System.out.println("Department " + dept + ": " + emp.orElse(null)));
    }
}
/*
Department 1: Charlie (Age: 50)
Department 2: Eve (Age: 35)
Department 3: David (Age: 40)
*/

Find Duplicate Elements in a List

Find all duplicate elements in a List<Integer>.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 2, 6, 3, 7, 8, 1, 9, 10, 6);

Set<Integer> seen = new HashSet<>();
List<Integer> duplicates = numbers.stream()
    .filter(n -> !seen.add(n)) // If add() returns false, it's a duplicate
    .distinct() // Ensure each duplicate appears only once in the result
    .collect(Collectors.toList());

System.out.println(duplicates); // [1, 2, 3, 6]

// Approach 2 without set
List<Integer> duplicates = numbers.stream()
    .collect(Collectors.groupingBy(n -> n, Collectors.counting())) // Count occurrences of each number
    .entrySet().stream() // Convert the map to a stream
    .filter(entry -> entry.getValue() > 1) // Keep only elements with count > 1 (duplicates)
    .map(Map.Entry::getKey) // Extract the keys (the duplicate numbers)
    .toList(); // Collect as a List

Convert a List of Employees into a Map

Convert List<Employee> into Map<Integer, String> where key is employeeId and value is employeeName.

Map<Integer, String> employeeMap = employees.stream()
    .collect(Collectors.toMap(Employee::getId, Employee::getName));

System.out.println(employeeMap); // {101=Alice, 102=Bob, 103=Charlie}

Find the Youngest Employee

Find the youngest employee in the company.

Employee youngestEmployee = employees.stream()
    .min(Comparator.comparingInt(Employee::getAge)) // Find the employee with the minimum age
    .orElse(null); // Return null if the list is empty

Find the Longest and Shortest Words in a Sentence

Given a sentence, find the longest and shortest words.

String sentence = "Java Streams are powerful and concise";

String max = Arrays.stream(sentence.split(" "))
    .max(Comparator.comparingInt(String::length))
    .get();

String min = Arrays.stream(sentence.split(" "))
    .min(Comparator.comparingInt(String::length))
    .get();

System.out.println("Longest Word: " + max); //Longest Word: powerful
System.out.println("Shortest Word: " + min); //Shortest Word: are

Find the Average Age of Employees by Department

Compute the average age of employees per department.

Map<Integer, Double> avgAgePerDepartment = employees.stream()
    .collect(Collectors.groupingBy(
        Employee::getDepartmentId, 
        Collectors.averagingInt(Employee::getAge)
    ));

Count the Occurrences of Each Character in a String

Given a String, count occurrences of each character.

String input = "banana";

Map<Character, Long> charCount = input.chars() // Convert String to IntStream of characters
    .mapToObj(c -> (char) c) // Convert int to Character
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); // Group and count occurrences

System.out.println(charCount); // {a=3, b=1, n=2}

Flatten a List of Lists

Convert List<List<Integer>> into a flat List<Integer>.

List<Integer> flatList = nestedList.stream()
    .flatMap(List::stream)
    .toList();

System.out.println(flatList);

Find Top 3 Highest Salaries

Find the top 3 highest salaries from List<Employee>.

List<Employee> topSalaries = employees.stream()
    .sorted(Comparator.comparingDouble(Employee::getSalary).reversed()) // Sort by salary in descending order
    .limit(3) // Get top 3
    .toList();

Convert a List of Objects to JSON String

Convert List<Employee> into a JSON-like String.

class Employee {
    private final String name;
    private final double salary;

    public Employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }

    public String toJson() {
        return String.format("{\"name\":\"%s\", \"salary\":%.2f}", name, salary);
    }
}

public class EmployeeJsonConverter {
    public static void main(String[] args) {
        List<Employee> employees = List.of(
            new Employee("Alice", 50000),
            new Employee("Bob", 60000),
            new Employee("Charlie", 70000)
        );

        String json = employees.stream()
            .map(Employee::toJson)
            .collect(Collectors.joining(", ", "[", "]"));

        System.out.println(json);
        // [{"name":"Alice", "salary":50000.00}, {"name":"Bob", "salary":60000.00}, {"name":"Charlie", "salary":70000.00}]
    }
}

Find All Employees Older Than 30 and Sort by Salary

Find employees older than 30 and sort them by salary.

List<Employee> filteredEmployees = employees.stream()
    .filter(emp -> emp.getAge() > 30) // Filter employees older than 30
    .sorted(Comparator.comparingDouble(Employee::getSalary)) // Sort by salary in ascending order
    .toList();

Find the Median Salary

Compute the median salary from List<Employee>.

OptionalDouble median = employees.stream()
    .mapToDouble(Employee::getSalary)
    .sorted()
    .skip((employees.size() - 1) / 2) // Skip first half for odd/even cases
    .limit(2 - employees.size() % 2) // Take 1 element if odd, 2 if even
    .average(); // Compute median

Sort a List of Employees by Multiple Criteria

Sort List<Employee> first by department, then by salary.

import java.util.*;
import java.util.stream.Collectors;

class Employee {
    String name;
    String department;
    double salary;

    public Employee(String name, String department, double salary) {
        this.name = name;
        this.department = department;
        this.salary = salary;
    }

    @Override
    public String toString() {
        return name + " (" + department + ", $" + salary + ")";
    }
}

public class EmployeeSorting {
    public static void main(String[] args) {
        List<Employee> employees = List.of(
                new Employee("Alice", "HR", 60000),
                new Employee("Bob", "IT", 75000),
                new Employee("Charlie", "IT", 72000),
                new Employee("David", "HR", 55000),
                new Employee("Eve", "Finance", 90000),
                new Employee("Frank", "Finance", 85000)
        );

        // Sorting using streams
        List<Employee> sortedEmployees = employees.stream()
                .sorted(Comparator.comparing(Employee::department)
                        .thenComparing(Employee::salary))
                .collect(Collectors.toList());

        // Print sorted employees
        sortedEmployees.forEach(System.out::println);
        // Output:
        // Frank (Finance, $85000.0)
        // Eve (Finance, $90000.0)
        // David (HR, $55000.0)
        // Alice (HR, $60000.0)
        // Charlie (IT, $72000.0)
        // Bob (IT, $75000.0)
    }
}

Find the First N Prime Numbers

Generate the first N prime numbers using Stream.iterate().

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

public class PrimeNumbersUsingStream {
    public static void main(String[] args) {
        int N = 10; // Change N to get more primes

        List<Integer> primes = Stream.iterate(2, i -> i + 1)  // Start from 2, increment by 1
                .filter(PrimeNumbersUsingStream::isPrime)      // Keep only prime numbers
                .limit(N)                                      // Take the first N primes
                .toList();                                     // Collect to a List (Java 16+)

        System.out.println("First " + N + " prime numbers: " + primes);
        // Output: First 10 prime numbers: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
    }

    // Method to check if a number is prime
    private static boolean isPrime(int num) {
        if (num < 2) return false;
        for (int i = 2; i <= Math.sqrt(num); i++) {
            if (num % i == 0) return false;
        }
        return true;
    }
}

Calculate Factorial Using Streams

Compute factorial of n using reduce().

int n = 5; // Change this value to compute factorial of a different number

int factorial = IntStream.rangeClosed(1, n) // Generates numbers from 1 to n
    .reduce(1, (a, b) -> a * b);        // Multiplies all elements

System.out.println("Factorial of " + n + " is: " + factorial);
// Output: Factorial of 5 is: 120

Check if a String is an Anagram of Another String

Verify if two given strings are anagrams.

import java.util.stream.Collectors;

public class AnagramChecker {
    public static void main(String[] args) {
        String str1 = "listen";
        String str2 = "silent";

        boolean isAnagram = areAnagrams(str1, str2);

        System.out.println(str1 + " and " + str2 + " are anagrams: " + isAnagram);
        // Output: listen and silent are anagrams: true
    }

    public static boolean areAnagrams(String str1, String str2) {
        if (str1.length() != str2.length()) return false; // Different lengths can't be anagrams

        return str1.chars().sorted()
                .mapToObj(c -> String.valueOf((char) c))
                .collect(Collectors.joining())
                .equals(
                    str2.chars().sorted()
                        .mapToObj(c -> String.valueOf((char) c))
                        .collect(Collectors.joining())
                );
    }
}

Find the Kth Largest Element in a List

Find the Kth largest number in a List<Integer>.

List<Integer> numbers = List.of(10, 5, 8, 20, 15, 3, 25);
int K = 3; // Change K to find a different Kth largest element

int kthLargest = numbers.stream()
                .sorted(Comparator.reverseOrder()) // Sort in descending order
                .skip(K - 1)                       // Skip (K-1) elements
                .findFirst()                       // Get the Kth element
                .orElseThrow(() -> new IllegalArgumentException("K is out of range"));

Generate a Fibonacci Series Using Streams

Generate Fibonacci numbers using Stream.iterate().

int n = 10; // Generate first N Fibonacci numbers

Stream.iterate(new long[]{0, 1}, fib -> new long[]{fib[1], fib[0] + fib[1]}) // Generate pairs
  .limit(n) // Limit to first N numbers
  .map(fib -> fib[0]) // Extract first element from pair
  .forEach(System.out::println);

// Output: 0 1 1 2 3 5 8 13 21 34

Find the Most Expensive Product in Each Category

Given a List<Product>, find the most expensive product in each category.

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

class Product {
    String name;
    String category;
    double price;

    public Product(String name, String category, double price) {
        this.name = name;
        this.category = category;
        this.price = price;
    }

    @Override
    public String toString() {
        return name + " ($" + price + ")";
    }
}

public class MostExpensiveProduct {
    public static void main(String[] args) {
        List<Product> products = List.of(
                new Product("Laptop", "Electronics", 1200),
                new Product("Smartphone", "Electronics", 900),
                new Product("TV", "Electronics", 1500),
                new Product("Blender", "Appliances", 300),
                new Product("Vacuum Cleaner", "Appliances", 400),
                new Product("Shampoo", "Personal Care", 15),
                new Product("Perfume", "Personal Care", 60)
        );

        Map<String, Product> mostExpensiveByCategory = products.stream()
                .collect(Collectors.toMap(
                        Product::category,                  // Group by category
                        Function.identity(),                // Keep the product
                        (p1, p2) -> p1.price > p2.price ? p1 : p2 // Keep the most expensive
                ));

        System.out.println("Most Expensive Product in Each Category: " + mostExpensiveByCategory);
        // Output: {Electronics=TV ($1500.0), Appliances=Vacuum Cleaner ($400.0), Personal Care=Perfume ($60.0)}
    }
}

Find Most Common Words in a Paragraph

Given a String paragraph, count occurrences of each word and sort by frequency.

String paragraph = "Java is great and Java is powerful. Java is fun and powerful.";

List<Map.Entry<String, Long>> sortedWordCount = Arrays.stream(paragraph.toLowerCase().split("\\W+"))
  .collect(Collectors.groupingBy(word -> word, Collectors.counting())) // Count occurrences
  .entrySet().stream()
  .sorted(Map.Entry.<String, Long>comparingByValue(Comparator.reverseOrder())) // Sort by frequency
  .toList(); // Collect as a list

System.out.println("Word frequencies sorted by count: " + sortedWordCount);
// Output: Word frequencies sorted by count: [java=3, is=3, powerful=2, and=2, great=1, fun=1]

Merge Two Sorted Lists into One Sorted List

Merge two sorted lists into a single sorted list.

List<Integer> list1 = List.of(1, 3, 5, 7, 9);
List<Integer> list2 = List.of(2, 4, 6, 8, 10);

List<Integer> mergedSortedList = Stream.concat(list1.stream(), list2.stream()) // Merge two lists
  .sorted() // Sort the merged stream
  .collect(Collectors.toList()); // Collect to a list

System.out.println("Merged Sorted List: " + mergedSortedList);
// Output: Merged Sorted List: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Check if a Sentence is a Pangram

Verify if a sentence contains every letter of the alphabet at least once.

import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class PangramChecker {
    public static void main(String[] args) {
        String sentence = "The quick brown fox jumps over the lazy dog";

        boolean isPangram = sentence.toLowerCase()
                .chars() // Convert to IntStream of characters
                .filter(Character::isLetter) // Keep only letters
                .mapToObj(c -> (char) c) // Convert int to Character
                .collect(Collectors.toSet()) // Collect unique letters
                .size() == 26; // Check if all 26 letters are present

        System.out.println("Is Pangram? " + isPangram);
        // Output: Is Pangram? true
    }
}

Find the Sum of All Even-Indexed Elements in a List

Sum all even-indexed elements in a list.

int sum = IntStream.range(0, numbers.size())  // Generate indices from 0 to size-1
                .filter(i -> i % 2 == 0)             // Keep only even indices
                .map(numbers::get)                   // Get the elements at those indices
                .sum();                              // Sum them up

Simulate a Voting System Using Streams

Given a list of votes, count occurrences of each candidate and determine the winner.

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class ElectionWinner {
    public static void main(String[] args) {
        List<String> votes = List.of("Alice", "Bob", "Alice", "Charlie", "Bob", "Alice", "Bob", "Bob");

        // Count occurrences of each candidate
        Map<String, Long> voteCount = votes.stream()
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        // Determine the winner (candidate with max votes)
        String winner = voteCount.entrySet().stream()
                .max(Map.Entry.comparingByValue()) // Get the entry with the highest count
                .map(Map.Entry::getKey)           // Extract the candidate's name
                .orElse("No votes");

        System.out.println("Vote counts: " + voteCount);
        // Output: Vote counts: {Alice=3, Bob=4, Charlie=1}

        System.out.println("Winner: " + winner);
        // Output: Winner: Bob
    }
}
PreviousCollectors Utility ClassNextFunctional Interfaces

Last updated 4 months ago

Was this helpful?