Skip to content

Instantly share code, notes, and snippets.

@asarkar
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asarkar/6daf5f137e1924772d52 to your computer and use it in GitHub Desktop.
Save asarkar/6daf5f137e1924772d52 to your computer and use it in GitHub Desktop.
Scala Collections Demo
public class Employee {
private Address addr;
private int age;
// Getters and setters
}
class Address {
private String streetAddr1;
private String streetAddr2;
private String city;
private int zipCode;
private String state;
// Getters and setters
}
public class HR {
private List<Employee> allEmployees = // HR knows how to find you
public static List<Employee> findAllEmployeesLivingInZipCode(int zipCode) {
List<Employee> employees = new ArrayList<>();
for (Employee e : allEmployees) {
if (e.getAddr().getzipCode() == zipCode) {
employees.add(e);
}
}
return employees;
}
public static int getAverageAge() {
long sum = 0;
for (Employee e : allEmployees) {
sum += e.getAge();
}
return sum / allEmployees.size();
}
}
object HR {
List[Employee] allEmployees = // HR knows how to find you
def findAllEmployeesLivingInZipCode(zipCode: Int) = {
allEmployees.filter(_.addr.zipCode == zipCode)
}
def getAverageAge = {
allEmployees.map(_.age).sum / allEmployees.size
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment