JavaTuples - Checking Elements


Advertisements

Each tuple provides utility methods to check their elements in similar fashion as collection.

  • contains(element) − checks if element is present or not.

  • containsAll(collection) − checks if elements are present or not.

  • indexOf(element) − returns the index of first element if present otherwise -1.

  • lastIndexOf(element) − returns the index of last element if present otherwise -1.

Pair<String, Integer> pair = Pair.with("Test", Integer.valueOf(5)); 
boolean isPresent = pair.contains("Test");

Example

Let's see JavaTuples in action. Here we'll see how to check elements in a tuple.

Create a java class file named TupleTester in C:\>JavaTuples.

File: TupleTester.java

package com.howcodex;
import java.util.List;
import org.javatuples.Quartet;
public class TupleTester {
   public static void main(String args[]){
      Quartet<String, Integer, String, String> quartet = Quartet.with(
         "Test1", Integer.valueOf(5), "Test3", "Test3"
      );
      System.out.println(quartet);
      boolean isPresent = quartet.contains(5);
      System.out.println("5 is present: " + isPresent);
      isPresent = quartet.containsAll(List.of("Test1", "Test3"));   
      System.out.println("Test1, Test3 are present: " + isPresent);
      int indexOfTest3 = quartet.indexOf("Test3");
      System.out.println("First Test3 is present at: " + indexOfTest3);
      int lastIndexOfTest3 = quartet.lastIndexOf("Test3");
      System.out.println("Last Test3 is present at: " + lastIndexOfTest3);
   }
}

Verify the result

Compile the classes using javac compiler as follows −

C:\JavaTuples>javac -cp javatuples-1.2.jar ./com/howcodex/TupleTester.java

Now run the TupleTester to see the result −

C:\JavaTuples>java  -cp .;javatuples-1.2.jar com.howcodex.TupleTester

Output

Verify the Output

[Test1, 5, Test3, Test3]
5 is present: true
Test1, Test3 are present: true
First Test3 is present at: 2
Last Test3 is present at: 3
Advertisements