Skip to content

Instantly share code, notes, and snippets.

@kazmura11
Last active August 29, 2015 14:13
Show Gist options
  • Save kazmura11/d048d53af0164d973d95 to your computer and use it in GitHub Desktop.
Save kazmura11/d048d53af0164d973d95 to your computer and use it in GitHub Desktop.
Mapの使いどき
package prin.com;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
// なんでこんな構造になっているのかっていうツッコミはあると思いますが
// 説明のため あくまで簡易的な例です。
// idはA00000の形式で作られていて最初のアルファベットで部署が紐づいている
// ということにします。
// 今回はA : 人事(Human Resources), B ; 研究開発(R&D), C; 営業(Sales) とします。
// 従業員
class Employee {
public Employee(String name, int age, String id) {
this.name = name;
this.age = age;
this.id = id;
}
public String name;
public int age;
public String id;
public String department;
}
public class MapTest {
private List<Employee> employees;
public MapTest() {
employees = new ArrayList<Employee>();
employees.add(new Employee("John", 29, "B10001"));
employees.add(new Employee("Chris", 26, "C10001"));
employees.add(new Employee("Cathy", 40, "C10002"));
}
// 愚直にif文に分ける例
public void example1() {
for (Employee e : employees) {
if (e.id.substring(0, 1).equals("A")) {
e.department = "Human Resources";
}
else if (e.id.substring(0, 1).equals("B")) {
e.department = "R&D";
}
else if (e.id.substring(0, 1).equals("C")) {
e.department = "Sales";
}
}
printDepartment();
}
// ちょっとましにした例 いや、example1のほうがましかも
public void example2() {
class DeptMap {
public DeptMap(String code, String department) {
this.code = code;
this.department = department;
}
public String code;
public String department;
}
// Listのほうがいいけどまぁ、配列で。
DeptMap[] dMap = {
new DeptMap("A", "HumanResources"),
new DeptMap("B", "R&D"),
new DeptMap("C", "Sales")
};
for (Employee e : employees) {
// 件数が少ないからシーケンシャルサーチで見つける
for (int i = 0; i < dMap.length; i++) {
if (e.id.substring(0, 1).equals(dMap[i].code)) {
e.department = dMap[i].department;
break;
}
}
}
printDepartment();
}
// もっともマシな書き方
public void example3() {
Map<String, String> dMap = new HashMap<String, String>();
dMap.put("A", "HumanResources");
dMap.put("B", "R&D");
dMap.put("C", "Sales");
for (Employee e : employees) {
e.department = dMap.get(e.id.substring(0, 1));
}
printDepartment();
}
private void printDepartment() {
for (Employee e : employees) {
System.out.println("Name : " + e.name + ",\tDept: " + e.department);
}
}
public static void main(String[] args) {
System.out.println(">> example1");
MapTest mt1 = new MapTest();
mt1.example1();
System.out.println(">> example2");
MapTest mt2 = new MapTest();
mt2.example2();
System.out.println(">> example3");
MapTest mt3 = new MapTest();
mt3.example3();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment