tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 
 Tools and Libs > Google Guava > Collections > Constrained Set

Constrained Set 

Google Guava is a java library with lot of utilities and reusable components. This requires the library guava-10.0.jar to be in classpath. The following example shows using Constraints.constrainedSet() API. It returns a constrained set which enforces a specific constraint on the set.

File Name  :  
com/bethecoder/tutorials/guava/collection_tests/ConstrainedSetTest.java 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
   
package com.bethecoder.tutorials.guava.collection_tests;

import java.util.HashSet;
import java.util.Set;

import com.bethecoder.tutorials.guava.common.Student;
import com.google.common.collect.Constraint;
import com.google.common.collect.Constraints;

public class ConstrainedSetTest {

  /**
   @param args
   */
  public static void main(String[] args) {
    
    Student student = new Student("Sriram"2"Chess");
    Student student2 = new Student("Charan"18"Cricket");
    
    Set<Student> childStudents = Constraints.constrainedSet(
        new HashSet<Student>()new KidConstraint());
    
    //Positive case
    childStudents.add(student);
    System.out.println(childStudents);
    
    //Negative case
    try {
      childStudents.add(student2);
    catch (RuntimeException e) {
      System.out.println(e);
    }
  }
}

class KidConstraint implements Constraint<Student> {
  @Override
  public Student checkElement(Student element) {
    if (!element.isKid()) {
      throw new RuntimeException("This collection accepts only kids");
    }
    return element;
  }
}
   

It gives the following output,
[com.bethecoder.tutorials.guava.common.Student@1a758cb]
java.lang.RuntimeException: This collection accepts only kids


                    Print

   



Books Recommendation

 
 
bl  br