DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Upender has posted 4 posts at DZone. View Full User Profile

Power of Guava Switcher

05.06.2014
| 5163 views |
  • submit to reddit
//Example-1
public class SwitcherDemo
{
	public static void main(String args[])
	{
		Switcher generic = new Switcher()
				.addCase(1, "Integer")
				.addCase(1.1, "Double")
				.addCase(1.1f,"Float")
				.addCase("S","String")
				.setDefault("Others");
		System.out.println("Switch type "+generic.exec(1.1f));
		System.out.println("Switch type "+generic.exec("S"));
		System.out.println("Switch type "+generic.exec(1));
		System.out.println("Switch type "+generic.exec(1.1));
		System.out.println("Switch type "+generic.exec("SS"));
	}
}

//Example-2
import ch.lambdaj.function.closure.Switcher;

import java.util.Arrays;
import java.util.List;

public class SwitcherDemo {



	public static void main(String args[])
	{
		Employee fulltime = new Employee(JOB_TYPE.FULL_TIME);
		Employee partime = new Employee(JOB_TYPE.PART_TIME);
		Employee contract = new Employee(JOB_TYPE.CONTRACT);
		Employee intern = new Employee(JOB_TYPE.INTERN);
		List<Employee>  employeeList = Arrays.asList(fulltime,partime,contract,intern);

		Switcher<Salary> salarySwitcher = new Switcher<Salary>();
		salarySwitcher.addCase(JOB_TYPE.FULL_TIME, new Salary(100000));
		salarySwitcher.addCase(JOB_TYPE.PART_TIME, new Salary(50000));
		salarySwitcher.addCase(JOB_TYPE.CONTRACT, new Salary(120000));
		salarySwitcher.addCase(JOB_TYPE.INTERN, new Salary(45000));
		salarySwitcher.setDefault(new Salary(0));

		for(Employee e: employeeList)
		{
                     Salary sal = salarySwitcher.exec(e.getJobtype());
			e.setSalary(sal);
			System.out.println("Salary "+e.getSalary().getSalary()+" Offered Job type "+e.getJobtype());
		}

	}
}
enum JOB_TYPE
{
	FULL_TIME,CONTRACT,INTERN,PART_TIME
}

class Employee
{

	private final JOB_TYPE jobtype;
	private Salary salary;

	Employee(JOB_TYPE job_type)
	{
		this.jobtype=job_type;
	}
	public JOB_TYPE getJobtype()
	{
		return jobtype;
	}

	Salary getSalary()
	{
		return salary;
	}

	void setSalary(Salary salary)
	{
		this.salary = salary;
	}
}
class Salary
{
	private final double sal;

	public Salary(double sal)
	{
		this.sal=sal;
	}
	public double getSalary()
	{
		return sal;
	}
}

In Java Switch has limitation i.e you can check case values integer , character, or string, etc.but you can't combine all these cases in single switch case. If you try to combine then it will show compilation error. So overcome this problem using Google Lamdaj Switcher class .  You case stick with one type value comparison or multiple type value comparison. The first example show to use multiple type cases and the second example show regular scenario to get salary based on job type.