Java UUID.compareTo(UUID val) method example

In this tutorial, You will learn how to compare two UUID's. Java UUID.compareTo(UUID val) method returns -1, 0 or 1 as this UUID is less than, equal to, or greater than val.

Compares this UUID with the specified UUID.

syntax

public int compareTo(UUID val)

Parameters

val - UUID to which this UUID is to be compared.

Returns

-1, 0 or 1 as this UUID is less than, equal to, or greater than val.

Java UUID compareTo(UUID val) example

  • UUID.fromString("6224c18d-d004-11bd-984e-b8d80b2bdff8"); It creates a UUID from the string standard representation.
  • uuid1.compareTo(uuid2); It will compare uuid1 to uuid2. In this case both are same.
  • uuid1.compareTo(uuid3); It will compare uuid1 to uuid3. In this case both are different.
package com.technicalkeeda;

import java.util.UUID;

public class App {

    public static void main(String[] args) {

        UUID uuid1 = UUID.fromString("6224c18d-d004-11bd-984e-b8d80b2bdff8");
        UUID uuid2 = UUID.fromString("6224c18d-d004-11bd-984e-b8d80b2bdff8");
        UUID uuid3 = UUID.fromString("5289df73-7df5-3326-bcdd-22597afb1fac");

        System.out.println("uuid1 compare to uuid2 : " + uuid1.compareTo(uuid2));
        System.out.println("uuid1 compare to uuid3 : " + uuid1.compareTo(uuid3));
    }
}

output

uuid1 compare to uuid2 : 0
uuid1 compare to uuid3 : 1