DEV Community

FUNDAMENTOS JAVA
FUNDAMENTOS JAVA

Posted on

2 1 1 1

6.3 Compondo comparators

1 Ordenando por Diferentes Critérios

  • Podemos ordenar usuários pelos pontos, evitando autoboxing com comparingInt:

usuarios.sort(Comparator.comparingInt(Usuario::getPontos));

2 Compondo Comparadores com thenComparing

  • Para ordenar por pontos e, em caso de empate, por nome:

Comparator<Usuario> c = Comparator.comparingInt(Usuario::getPontos)
.thenComparing(Usuario::getNome);
usuarios.sort(c);

  • Há métodos equivalentes como thenComparingInt para evitar boxing.

3 Lidando com Valores null

  • Para mover valores null para o final da lista:

usuarios.sort(Comparator.nullsLast(Comparator.comparing(Usuario::getNome)));

  • O método nullsFirst faz o contrário, colocando null no início.

4 Ordenando em Ordem Decrescente

  • Usamos reversed() no Comparator:

usuarios.sort(Comparator.comparing(Usuario::getPontos).reversed());

5 Explorando Novos Métodos

  • A API de Comparator traz muitas melhorias, e é importante pesquisar e experimentar para evitar escrever código desnecessário.

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)

Hot sauce if you're wrong - web dev trivia for staff engineers

Hot sauce if you're wrong · web dev trivia for staff engineers (Chris vs Jeremy, Leet Heat S1.E4)

  • Shipping Fast: Test your knowledge of deployment strategies and techniques
  • Authentication: Prove you know your OAuth from your JWT
  • CSS: Demonstrate your styling expertise under pressure
  • Acronyms: Decode the alphabet soup of web development
  • Accessibility: Show your commitment to building for everyone

Contestants must answer rapid-fire questions across the full stack of modern web development. Get it right, earn points. Get it wrong? The spice level goes up!

Watch Video 🌶️🔥

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay