CodingBat: Java. Map-1


For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.


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;
  
}

For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.


3 thoughts on “CodingBat: Java. Map-1

  1. Emi

    My solution for mapAB2:

    public Map mapAB2(Map map) {
    if (map.get(“a”) != null && map.get(“b”) != null && map.get(“b”).equals(map.get(“a”))) {
    map.remove(“a”);
    map.remove(“b”);
    }
    return map;
    }

    Reply

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.

This site uses Akismet to reduce spam. Learn how your comment data is processed.