How to Compare Objects with Oracle JDK

JDK 8

import static java.lang.System.out;

import java.util.Arrays;

public final class JdkSample {

  public static void main(final String[] args) {
    final String[] names = { "Fernando", "Kusuma", "Karina" };

    Arrays.sort(names, (o1, o2) -> o1.compareTo(o2));

    for (int i = 0; i < names.length; i++)
      out.println(names[i]);

  }

}

JDK 7

import static java.lang.System.out;

import java.util.Arrays;
import java.util.Comparator;

public final class JdkSample {

  public static void main(final String[] args) {
    final String[] names = { "Fernando", "Kusuma", "Karina" };

    Arrays.sort(names, new Comparator<String>() {

      public int compare(final String o1, final String o2) {
        return o1.compareTo(o2);
      }

    });

    for (int i = 0; i < names.length; i++)
      out.println(names[i]);

  }

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s