tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | 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  :  
Author  :  Sudhakar KV
Email  :  [email protected]
package com.bethecoder.tutorials.guava.collection_tests;

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

import com.bethecoder.tutorials.guava.common.Student;

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
    //Negative case
    try {
    catch (RuntimeException e) {

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

It gives the following output,
java.lang.RuntimeException: This collection accepts only kids


bl  br