Question

Can someone help me with this code, I not really understanding how to do this? import...

Can someone help me with this code, I not really understanding how to do this?

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
* @version Spring 2019
* @author Kyle
*/
public class MapProblems {

/**
* Modify and return the given map as follows: if the key "a" has a value, set the key "b" to
* have that value, and set the key "a" to have the value "". Basically "b" is confiscating the
* value and replacing it with the empty string.
*
* @param map to be edited
* @return map
*/
public Map<String, String> confiscate(Map<String, String> map) {
if (map.containsKey("a") && map.containsValue("a")) {

}
}

/**
* Modify and return the given map as follows: if the key "duck" has a value, set the key
* "goose" to have that same value. In all cases remove the key "swan", the rest of the map
* should not change.
*
* @param map to be edited
* @return map
*/
public Map<String, String> mapBird1(Map<String, String> map) {
throw new UnsupportedOperationException("Not supported yet");
}

/**
* Given a map of bird keys and topping values, modify and return the map as follows: if the key
* "turkey" has a value, set that as the value for the key "chicken". If the key "vulture" has a
* value, set that as the value for the key "buzzard".
*
* @param map to be edited
* @return map
*/
public Map<String, String> mapBird2(Map<String, String> map) {
throw new UnsupportedOperationException("Not supported yet");
}

/**
* Given an array of strings, return a Map<String, Integer> with a key for each different
* string, with the value the number of times that string appears in the array.
*
* @param strings array
* @return map
*/
public Map<String, Integer> wordCount(ArrayList<String> strings) {
throw new UnsupportedOperationException("Not supported yet");
}

/**
* Given an ArrayList of Strings, create a new map that creates a key for each String by
* multiplying it's length by 7. If a key is already being used do not add the new value.
*
* @param str ArrayList of Strings
* @return new Map
*/
public Map<Integer, String> intMap(ArrayList<String> str) {
throw new UnsupportedOperationException("Not supported yet");
}

/**
* Caiomhe has tons of Student Records that need to be organized. She wants you to put all these
* Records into a Map. The StudentRecord class already has a hashCode method that should be used
* to create keys. Store all the StudentRecord objects in a new map and then return it.
*
* @param students ArrayList of StudentRecord objects
* @return map
*/
public Map<Integer, StudentRecord> recordMap(ArrayList<StudentRecord> students) {
throw new UnsupportedOperationException("Not supported yet");
}
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Map:

Map is a collection in java where it contains (key, value) pairs.

Few methods of Map used in the code:

  1. get: Get method returns a value corresponding to a key in the map. If no entry exists with the provided key, it returns null. Example: Assume a map with <String, Integer> key, value pairs. To get value of key "a" in a map, then map.get("a") returns the Integer corresponding to "a" or returns null if no entry exists in map with key "a"
  2. put: Put method sets a value to a key. If key does not exist in map previously then it creates a new entry with key and value provided, If the map contains an entry for key then the value corresponding to key will be updated. Example: Assume a map with <String, Integer> key, value pairs. Then map.put("a", 1), creates a new entry if the map as it do not contain any value for "a", updates the value of "a" if map already contains some integer corresponding to "a"
  3. containsKey: ContainsKey method returns true if the map contains the key, or else returns false.
  4. containsValue: ContainsValue checks whether the value provided is mapped to one or more keys. Returns true if already mapped to one or more keys, else returns false.
  5. remove: map.remove("a") removes any entry corresponding to the key "a".

Program:

Note: Program is explained using comments in the code.

import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class MapProblems { /** * Modify and retur// Check if map contains a value for duck if(map.containsKey(duck) && map.get(duck) != null) { // Copy the value of duck* @return map * public Map<String, Integer> wordcount(ArrayList<String> strings) { //create a new hash map to store the countif(!map.containskey(7 * string.length()) { map.put(7 * string. length(), string); return map; * Caiomhe has tons of Student R//test mapBird1 map = new HashMap<>(); map.put(duck, I am a duck); map.put(swan, I will get killed); System.out.print//Unable to test recordMap method as StudentRecord definition is not provided

Code:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class MapProblems {

   /**
   * Modify and return the given map as follows: if the key "a" has a value, set the key "b" to
   * have that value, and set the key "a" to have the value "". Basically "b" is confiscating the
   * value and replacing it with the empty string.
   *
   * @param map to be edited
   * @return map
   */
   public Map<String, String> confiscate(Map<String, String> map) {
       // First find whether map conatins key "a"
       // Then the second condition is to verify that the value corresponding to "a"
       // is not null.
       // Assuming the statement if the key "a" has a value means key "a" has some value(not null)
       if (map.containsKey("a") && map.get("a") != null) {
           // b confiscating value of a
           map.put("b", map.get("a"));
           // updating value of a to ""
           map.put("a", "");
       }
       return map;
   }

   /**
   * Modify and return the given map as follows: if the key "duck" has a value, set the key
   * "goose" to have that same value. In all cases remove the key "swan", the rest of the map
   * should not change.
   *
   * @param map to be edited
   * @return map
   */
   public Map<String, String> mapBird1(Map<String, String> map) {
       // Check if map contains a value for duck
       if(map.containsKey("duck") && map.get("duck") != null){
           // Copy the value of duck to goose
           map.put("goose", map.get("duck"));
       }
       // Remove the key swan
       map.remove("swan");
       return map;
   }

   /**
   * Given a map of bird keys and topping values, modify and return the map as follows: if the key
   * "turkey" has a value, set that as the value for the key "chicken". If the key "vulture" has a
   * value, set that as the value for the key "buzzard".
   *
   * @param map to be edited
   * @return map
   */
   public Map<String, String> mapBird2(Map<String, String> map) {
       //Check if turkey has a value
       if(map.containsKey("turkey") && map.get("turkey") != null){
           // set the value of turkey for chicken
           map.put("chicken", map.get("turkey"));
       }
       // check if vulture has a value in map
       if(map.containsKey("vulture") && map.get("vulture") != null){
           // set the value of vulture to buzzard
           map.put("buzzard", map.get("vulture"));
       }
       return map;
   }

   /**
   * Given an array of strings, return a Map<String, Integer> with a key for each different
   * string, with the value the number of times that string appears in the array.
   *
   * @param strings array
   * @return map
   */
   public Map<String, Integer> wordCount(ArrayList<String> strings) {
       //create a new hash map to store the count of each word
       HashMap<String, Integer> map = new HashMap<>();
      
       //iterate over the list using a for-each loop
       for(String key : strings){
           //get the value for key
           Integer count = map.get(key);
          
           //if count is null then set count to 0 as key is not present in the map
           if(count == null)
               count = 0;
              
           // put the value of key as count+1
           map.put(key, count+1);
       }
       return map;
   }

   /**
   * Given an ArrayList of Strings, create a new map that creates a key for each String by
   * multiplying it's length by 7. If a key is already being used do not add the new value.
   *
   * @param str ArrayList of Strings
   * @return new Map
   */
   public Map<Integer, String> intMap(ArrayList<String> str) {
       //Create a hash map to store the specified map above
       HashMap<Integer, String> map = new HashMap<>();
      
       //iterate over the list using for-each loop
       for(String string : str){
           //Check if the map contains 7 times length of stirng as key
           // If key is not present set the string as value to key
           // Skip if 7 times lenght is already present in the map as key
           if(!map.containsKey(7 * string.length())){
               map.put(7 * string.length(), string);
           }
       }
       return map;
   }

   /**
   * Caiomhe has tons of Student Records that need to be organized. She wants you to put all these
   * Records into a Map. The StudentRecord class already has a hashCode method that should be used
   * to create keys. Store all the StudentRecord objects in a new map and then return it.
   *
   * @param students ArrayList of StudentRecord objects
   * @return map
   */
   public Map<Integer, StudentRecord> recordMap(ArrayList<StudentRecord> students) {
       //Create a map to store hashCode StudentRecord mapping
       HashMap<Integer, StudentRecord> map = new HashMap<>();
      
       //Iterate over StudentRecord list
       for(StudentRecord studentRecord : students){
           //Add entry for each studentRecord to map with hashCode as key
           map.put(studentRecord.hashCode(), studentRecord);
       }
       return map;
   }
  
   //Main method
   public static void main(String[] ar){
       MapProblems mapProblems = new MapProblems();
      
       //test confiscate
       Map<String, String> map = new HashMap<>();
       map.put("a", "Hello");
       System.out.println("Before confiscate: "+ map);
       map = mapProblems.confiscate(map);
       System.out.println("After confiscate: "+ map);
      
       //test mapBird1
       map = new HashMap<>();
       map.put("duck", "I am a duck");
       map.put("swan", "I will get killed");
       System.out.println("\nBefore mapBird1: "+ map);
       map = mapProblems.mapBird1(map);
       System.out.println("After mapBird1: "+ map);
      
       //test mapBird2
       map = new HashMap<>();
       map.put("turkey", "This is a turkey");
       map.put("vulture", "I will get killed");
       System.out.println("\nBefore mapBird2: "+ map);
       map = mapProblems.mapBird2(map);
       System.out.println("After mapBird2: "+ map);
      
       //test wordCount
       ArrayList<String> words = new ArrayList<String>();
       words.add("Apple");
       words.add("Ball");
       words.add("Cat");
       words.add("Apple");
       words.add("Ball");
       words.add("Apple");
       words.add("Ball");
       words.add("Ball");
       words.add("Cat");
       Map<String, Integer> wordCountsMap = mapProblems.wordCount(words);
       System.out.println("\nWord Counts: "+ wordCountsMap);
      
       //test intMap
       words = new ArrayList<String>();
       words.add("Apple");
       words.add("Ball");
       words.add("Cat");
       Map<Integer, String> intMapOutput = mapProblems.intMap(words);
       System.out.println("\nInt map method output: "+ intMapOutput);
      
       //Unable to test recordMap method as StudentRecord definition is not provided
   }
}

Output:

Added a main method in the above code to test the methods in MapProblems class.

File Edit View Search Terminal Help Before confiscate: {a=Hello} After confiscate: {a=, b=Hello} Before mapBirdl: {duck=I am

import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class MapProblems { /** * Modify and return the given map as follows: if the key "a" has a value, set the key "b" to * have that value, and set the key "a" to have the value "". Basically "b" is confiscating the * value and replacing it with the empty string. * @param map to be edited * @return map public Map<String, String> confiscate(Map<String, String> map) { // First find whether map conatins key "a" // Then the second condition is to verify that the value corresponding to "a" // is not null. // Assuming the statement if the key "a" has a value means key "a" has some value (not null) if (map.containsKey("a") && map.get("a") != null) {/ // b confiscating value of a map.put("b", map.get("a")); // updating value of a to" map.put("a", ""); return map; /** * Modify and return the given map as follows: if the key "duck" has a value, set the key * "goose" to have that same value. In all cases remove the key "swan", the rest of the map * should not change. * @param map to be edited * @return map public Map<String, String> mapBird1(Map<String, String> map) {

We were unable to transcribe this image

* @return map * public Map<String, Integer> wordcount(ArrayList<String> strings) { //create a new hash map to store the count of each word HashMap<String, Integer> map = new HashMap<>(); //iterate over the list using a for-each loop for(String key : strings) { //get the value for key Integer count = map.get(key); //if count is null then set count to o as key is not present in the map if(count == null) count = 0; // put the value of key as count+1 map.put(key, count+1); return map; * Given an ArrayList of Strings, create a new map that creates a key for each string by * multiplying it's length by 7. If a key is already being used do not add the new value. * @param str ArrayList of Strings * @return new Map public Map<Integer, String> intMap(ArrayList<String> str) { //Create a hash map to store the specified map above HashMap<Integer, String> map = new HashMap<>(); //iterate over the list using for each loop for(String string : str) { //Check if the map contains 7 times length of stirng as key // If key is not present set the string as value to key // skip if 7 times lenght is already present in the map as key

if(!map.containskey(7 * string.length()) { map.put(7 * string. length(), string); return map; * Caiomhe has tons of Student Records that need to be organized. She wants you to put all these * Records into a Map. The StudentRecord class already has a hashCode method that should be used * to create keys. Store all the studentRecord objects in a new map and then return it. * @param students ArrayList of StudentRecord objects * @return map public Map<Integer, StudentRecord> recordMap(ArrayList<StudentRecord students) { //Create a map to store hashCode StudentRecord mapping HashMap<Integer, StudentRecord> map = new HashMap<>(); //Iterate over StudentRecord list for(StudentRecord studentRecord : students) { //Add entry for each studentRecord to map with hashCode as key map.put(studentRecord.hashCode(), studentRecord); return map; //Main method public static void main(String[] ar) { MapProblems mapProblems = new MapProblems(); //test confiscate Map<String, String> map = new HashMap<>(); map.put("a", "Hello"); System.out.println("Before confiscate: "+ map; map = mapProblems.confiscate (map); System.out.println("After confiscate: "# map);

//test mapBird1 map = new HashMap<>(); map.put("duck", "I am a duck"); map.put("swan", "I will get killed"); System.out.println("\nBefore mapBirdi: "+ map); map = mapProblems.mapBird1(map); System.out.println("After mapBirdi: "+ map); //test mapBird2 map = new HashMap<>(); map.put("turkey", "This is a turkey"); map.put("vulture", "I will get killed"); System.out.println("\nBefore mapBird2: "+ map); map = mapProblems.mapBirdz (map); System.out.println("After mapBird2: "+ map); //test wordcount ArrayList<String> words = new ArrayList<String>(); words.add("Apple"); words.add("Ball"); words.add("Cat"); words.add("Apple"); words.add("Ball"); words.add("Apple"); words.add("Ball"); words.add("Ball"); words.add("Cat"); Map<String, Integer> wordCountsMap = mapProblems.wordCount(words); System.out.println("\nWord counts: "+ wordCountsMap); //test intMap words = new ArrayList<String>(); words.add("Apple"); words.add("Ball"); words.add("Cat"); Map<Integer, String> intMapoutput = mapProblems. intMap(words); System.out.println("\nInt map method output: " + intMapoutput);

//Unable to test recordMap method as StudentRecord definition is not provided

We were unable to transcribe this image

We were unable to transcribe this image

We were unable to transcribe this image

We were unable to transcribe this image

if(!map.containskey(7 * string.length()) { map.put(7 * string. length(), string); return map; * Caiomhe has tons of Student Records that need to be organized. She wants you to put all these * Records into a Map. The StudentRecord class already has a hashCode method that should be used * to create keys. Store all the studentRecord objects in a new map and then return it. * @param students ArrayList of StudentRecord objects * @return map public Map<Integer, StudentRecord> recordMap(ArrayList<StudentRecord students) { //Create a map to store hashCode StudentRecord mapping HashMap<Integer, StudentRecord> map = new HashMap<>(); //Iterate over StudentRecord list for(StudentRecord studentRecord : students) { //Add entry for each studentRecord to map with hashCode as key map.put(studentRecord.hashCode(), studentRecord); return map; //Main method public static void main(String[] ar) { MapProblems mapProblems = new MapProblems(); //test confiscate Map<String, String> map = new HashMap<>(); map.put("a", "Hello"); System.out.println("Before confiscate: "+ map; map = mapProblems.confiscate (map); System.out.println("After confiscate: "# map);

We were unable to transcribe this image

//Unable to test recordMap method as StudentRecord definition is not provided

File Edit View Search Terminal Help Before confiscate: {a=Hello} After confiscate: {a=, b=Hello} Before mapBirdl: {duck=I am a duck, swan=I will get killed} After mapBird1: {duck=I am a duck, goose=I am a duck} Before mapBird2: {turkey=This is a turkey, vulture I will get killed} After mapBird2: {chicken=This is a turkey, turkey=This is a turkey, buzzard=I will get killed, vulture=1 will get killed} Word Counts: {Ball=4, Apple=3, Cat=2} Int map method output: {35=Apple, 21=Cat, 28=Ball}, '(program exited with code: 0 Press return to continue

Add a comment
Know the answer?
Add Answer to:
Can someone help me with this code, I not really understanding how to do this? import...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • // can someone explain the code line by line shortly.thanks import java.security.KeyPair; import ...

    // can someone explain the code line by line shortly.thanks import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import java.util.Base64; import java.util.HashMap; import java.util.Map; import javax.crypto.Cipher; // Java 8 example for RSA encryption/decryption. // Uses strong encryption with 2048 key size. public class GlobalMembers { public static void main(String[] args) throws Exception { String plainText = "Hello World!"; // Generate public and private keys using RSA Map<String, Object> keys = getRSAKeys(); PrivateKey privateKey = (PrivateKey) keys.get("private"); PublicKey publicKey = (PublicKey)...

  • Can someone please explain this piece of java code line by line as to what they...

    Can someone please explain this piece of java code line by line as to what they are doing and the purpose of each line (you can put it in the code comments). Code: import java.util.*; public class Array { private Integer[] array; // NOTE: Integer is an Object. Array() {     super();     array = new Integer[0]; } Array(Array other) {     super();     array = other.array.clone(); // NOTE: All arrays can be cloned. } void add(int value) {    ...

  • Would someone help please, with code to finish. Iterator and entrySet, I need help. please ```...

    Would someone help please, with code to finish. Iterator and entrySet, I need help. please ``` package coll.MapSet; import java.util.*; public class MapSet extends AbstractMap> implements Iterable { private Map> mapset = new HashMap<>(); /* Implement addValue such that calling this method adds the given value to the HashSet associated with the given key. This method must have the following signature: addValue(K key, V value) */ public void addValue(K key, V value) { // If the set has the key,...

  • PLEASE COMPLETE THE CODES. package javaprogram; import java.io.PrintStream; import java.util.ArrayList; import java.util.Scanner; /** * Movie class...

    PLEASE COMPLETE THE CODES. package javaprogram; import java.io.PrintStream; import java.util.ArrayList; import java.util.Scanner; /** * Movie class definition. * * @author David Brown * @version 2019-01-22 */ public class Movie implements Comparable { // Constants public static final int FIRST_YEAR = 1888; public static final String[] GENRES = { "science fiction", "fantasy", "drama", "romance", "comedy", "zombie", "action", "historical", "horror", "war" }; public static final int MAX_RATING = 10; public static final int MIN_RATING = 0; /** * Converts a string of...

  • complete this in java import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class...

    complete this in java import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class WordDetective { /** * Picks the first unguessed word to show. * Updates the guessed array indicating the selected word is shown. * * @param wordSet The set of words. * @param guessed Whether a word has been guessed. * @return The word to show or null if all have been guessed. */ public static String pickWordToShow(ArrayList<String> wordSet, boolean []guessed) { return null; //TODO...

  • JAVA programming 9.9 Ch 9, Part 2: ArrayList Searching import java.util.ArrayList; public class ArrayListSet {    ...

    JAVA programming 9.9 Ch 9, Part 2: ArrayList Searching import java.util.ArrayList; public class ArrayListSet {     /**      * Searches through the ArrayList arr, from the first index to the last, returning an ArrayList      * containing all the indexes of Strings in arr that match String s. For this method, two Strings,      * p and q, match when p.equals(q) returns true or if both of the compared references are null.      *      * @param s The string...

  • I need help running this code. import java.util.*; import java.io.*; public class wordcount2 {     public...

    I need help running this code. import java.util.*; import java.io.*; public class wordcount2 {     public static void main(String[] args) {         if (args.length !=1) {             System.out.println(                                "Usage: java wordcount2 fullfilename");             System.exit(1);         }                 String filename = args[0];               // Create a tree map to hold words as key and count as value         Map<String, Integer> treeMap = new TreeMap<String, Integer>();                 try {             @SuppressWarnings("resource")             Scanner input = new Scanner(new File(filename));...

  • Need Help Using Java programming only import java.util.ArrayList; //Import anything you need here public class Dictionary...

    Need Help Using Java programming only import java.util.ArrayList; //Import anything you need here public class Dictionary {     // Declare any variables you feel necessary here     public Dictionary(/*DO NOT PUT ANY PARAMETERS HERE!*/) {         // Initialise those variables     }     /***      * @return number of terms currently in the dictionary hint: starts at 0 when      *         there are no terms      */     public int numberOfTerms() {         return 0;     }     /***     ...

  • This is my code that i need to finish. In BoxRegion.java I have no idea how...

    This is my code that i need to finish. In BoxRegion.java I have no idea how to create the constructor. I tried to use super(x,y) but It is hard to apply. And Also In BoxRegionHashTable, I don't know how to create displayAnnotation BoxRegion.java ------------------------------------------------ public final class BoxRegion { final Point2D p1; final Point2D p2; /** * Create a new 3D point with given x, y and z values * * @param x1, y1 are the x,y coordinates for point...

  • complete this in java import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class...

    complete this in java import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class WordDetective { /** * Picks the first unguessed word to show. * Updates the guessed array indicating the selected word is shown. * * @param wordSet The set of words. * @param guessed Whether a word has been guessed. * @return The word to show or null if all have been guessed. */    public static String pickWordToShow(ArrayList<String> wordSet, boolean []guessed) { return null;...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT