CodingBat: Java. Map-1

Nick Parlante updated CodingBat with two new sets of Java exercises, which both focus on maps. My solutions for Map-1 are below.

mapBully:

public Map<String, String> mapBully(Map<String, String> map) {
  
  if (map.containsKey("a")) {
    String tmp = map.get("a");
    map.put("a", "");
    map.put("b", tmp);
  }
  
  return map;
}

mapShare:

public Map<String, String> mapShare(Map<String, String> map) {
  
  if (map.containsKey("a")) {
    String tmp = map.get("a");
    map.put("b", tmp);
  }
  
  map.remove("c");
      
  return map;
}

mapAB:

public Map<String, String> mapAB(Map<String, String> map) {
  
  if (map.containsKey("a") && map.containsKey("b")) {
    String tmp = map.get("a") + map.get("b");
    map.put("ab", tmp);
  }
  
  return map;
}

topping1:

public Map<String, String> topping1(Map<String, String> map) {
  
  if (map.containsKey("ice cream")) {
    map.put("ice cream", "cherry");
  }
  
  map.put("bread", "butter");
  
  return map;
}

topping2:

public Map<String, String> topping2(Map<String, String> map) {
  
  if (map.containsKey("ice cream")) {
    map.put("yogurt", map.get("ice cream"));
  }
  
  if (map.containsKey("spinach")) {
    map.put("spinach", "nuts");
  }

  return map;
}

topping3:

public Map<String, String> topping3(Map<String, String> map) {
  
  if (map.containsKey("potato")) {
    map.put("fries", map.get("potato"));
  }
  
  if (map.containsKey("salad")) {
    map.put("spinach", map.get("salad"));
  }

  return map;
  
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Spammer prevention; the answer is an integer: * Time limit is exhausted. Please reload CAPTCHA.