DEV Community

Cover image for Lista em Java Sem Valores Repetidos
Antonio Serra
Antonio Serra

Posted on

2 1 1 1 1

Lista em Java Sem Valores Repetidos

Listas com objetos não repetidos

Você não precisa fazer um ArrayList e verificar se o valor já existe na sua lista, há uma forma mais simples.

Vamos usar a interface Set e implementar com o HashSet.

Image HashSet

Agora vamos adicionar valores

Image HashSet Add

Repare que tentamos inserir o valor "Lucas" duas vezes.

Agora vamos imprimir os valores no nosso console

Vou apresentar a vocês duas maneiras de fazer isso:

  • Iterator
    A forma mais comum é declarar um Iterator e usar o .next() para receber os próximos valores dentro do (while).
    Image Iterator

  • Lambda
    A forma mais fácil (na minha opnião) é usar o forEach com expressão lambda
    Image lambda

Saída

Note que o nome Lucas só irá aparecer uma vez.

Image saida

Código Fonte disponível aqui: https://github.com/antoniorws/basic-java-trail

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay