# java.lang.IllegalStateException

**Code:** `IllegalStateException` · **Category:** Java · **Seen on:** Java

A method was called when the object wasn’t in the right state for it.

## Meaning

Examples: iterator.remove() twice, writing to a committed HTTP response, Optional.get misuse in some libraries, Spring context not refreshed. The message explains the state problem.

## Common causes

- Calling methods out of order
- Response already committed (servlets)
- Stream already operated upon or closed
- Duplicate keys in Collectors.toMap

## Quick fix

1. Read the message for the expected state
2. Don’t reuse streams
3. Pass a merge function to Collectors.toMap

## Detailed fix by platform

### Java

1. `Collectors.toMap(User::getEmail, u -> u, (a, b) -> a)`

## How to diagnose

1. **Message** — Which state is wrong?
2. **Order** — Which call came before?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/java/illegalstateexception)
