18--Map set related exercises

Posted by jumphopper on Mon, 22 Jun 2020 05:20:24 +0200

Exercise 1: features of Map interface

  • Please briefly describe the characteristics of Map

    Each element of Map consists of key and value
     Map key cannot be repeated. Each key corresponds to a value
     Key and value can be null
    

Exercise 2: Entry key to object

  • How the Entry key value traverses the Map set

     There are two kinds of objects stored in Map, one is called key and the other is called value,
     They are one-to-one correspondence in the Map. This pair of objects is also called an entry in the Map.
     Entry encapsulates the corresponding relationship of key value pairs into objects. That is, the key value pair object, so when we traverse the Map set,
     The corresponding key and value can be obtained from each key value pair (Entry) object.
    

Exercise 3: common methods in Map interface

  • Please use the method of Map collection to add elements, delete according to keys, and get values according to keys
public class MapTest01{
public static void main(String[] args) {
// 1. Create a HashMap
HashMap<String, String> hm = new HashMap<String, String>();


// 2. Use put to add elements

hm.put("Huang Xiaoming", "Baby");

        hm.put("Deng Chao", "Sun Li");

        hm.put("Li Chen", "Fan Bingbing");

        hm.put("Black bull", "Fan Bingbing");


// 3. Use put to modify elements

String v1 = hm.put("Li Chen", "Lilywhites ");


// 4. Use get to get elements

String string = hm.get("Black bull");


// 5. Use remove to delete elements

String v2 = hm.remove("Black bull");

        System.out.println(v2);


// 6. Print elements in set

System.out.println(hm);

    }

}

Exercise 4: Methods in the Map interface

  • Add several elements to a Map collection. Get all the values in the Map and use the enhanced for and iterator to iterate through each value.
public class MapTest02 {

public static void main(String[] args) {

// 1. Create a HashMap

HashMap<String, String> hm = new HashMap<String, String>();


// 2. Use put to add elements

hm.put("Huang Xiaoming", "Baby");

        hm.put("Deng Chao", "Sun Li");

        hm.put("Li Chen", "Fan Bingbing");

        hm.put("Black bull", "Fan Bingbing");


// 3. Use the values method of Map to get all values

Collection<String> values = hm.values();


// 4. Use enhanced for to get each value

for (String value : values) {

            System.out.println(value);

        }


        System.out.println("----------------");

// 5. Use iterator to get each value

Iterator<String> itr = values.iterator();

while (itr.hasNext()) {

            System.out.println(itr.next());

        }

    }

}

Exercise 5: HashMap storage key yes, custom object value yes, String

  • Please use the Map set to store the custom data type Car as the key and the corresponding price as the value. And use keySet and entrySet to traverse the Map set.
    Automobile:
// 1. Define automobile class. Include name and price attributes, override hashCode and equals methods

public class Car {


private String name;


private String color;


public Car() {

    }


public Car(String name, String color) {

this.name = name;

this.color = color;

    }


public String getName() {

return name;

    }


public void setName(String name) {

this.name = name;

    }


public String getColor() {

return color;

    }


public void setColor(String color) {

this.color = color;

    }


@Override

public boolean equals(Object o) {

if (this == o) return true;

if (!(o instanceof Car)) return false;


        Car car = (Car) o;


if (name != null ? !name.equals(car.name) : car.name != null) return false;

return color != null ? color.equals(car.color) : car.color == null;

    }


@Override

public int hashCode() {

int result = name != null ? name.hashCode() : 0;

        result = 31 * result + (color != null ? color.hashCode() : 0);

return result;

    }

}

Test class:

public class MapTest03 {

public static void main(String[] args) {

// 2. Create a HashMapkey to save the car object. value is the car price

HashMap<Car, Integer> hm = new HashMap<>();


// 3. Add car to HashMap

Car c1 = new Car("Changan Benben", "yellow");

        Car c3 = new Car("Chery  QQ", "black");

        Car c2 = new Car("Suzuki Alto ", "white");


        hm.put(c1, 10000);

        hm.put(c2, 20000);

        hm.put(c3, 30000);


// 4. Use keySet to traverse Map

Set<Car> keySet = hm.keySet();

for (Car c : keySet) {

// Get value according to key

Integer value = hm.get(c);

            System.out.println(c.getName() + ","+ c.getPrice() + " - "+ value);

        }


        System.out.println("-------------");


// 5. Use entrySet to traverse Map

Set<Map.Entry<Car, Integer>> entrySet = hm.entrySet();

for (Map.Entry<Car, Integer> entry : entrySet) {

            Car key = entry.getKey();

            Integer value = entry.getValue();

            System.out.println(key.getName() + ","+ key.getPrice() + " - "+ value);

        }

    }

}

Exercise 6: using Map sets (1)

  • Now there is a map set as follows:
Map<Integer,String> map = new HashMap<Integer, String>();
        map.put(1, "Zhang Sanfeng");
        map.put(2, "Zhou Zhiruo");
        map.put(3, "Wang Feng");
        map.put(4, "Exterminate abbess");

requirement:

	1. Traverse the set and print the serial number and the corresponding person name.
	2. Insert a message with the code of 5 and the name of Li Xiaohong into the map set
	3. Remove the information No. 1 in the map
    4. Change the name information No. 2 in the map set to "Zhou Lin"
public class MapTest04 {

public static void main(String[] args) {

// 1. Define HashMap, with number as key and name as value

Map<Integer,String> map = new HashMap<Integer, String>();


// 2. Use put method to add elements

map.put(1, "Zhang Sanfeng");

        map.put(2, "Zhou Zhiruo");

        map.put(3, "Wang Feng");

        map.put(4, "Exterminate abbess");


// 3. Use keySet + to enhance for to iterate the elements in the map and print

Set<Integer> keySet = map.keySet();

for (Integer key : keySet) {

            String value = map.get(key);

            System.out.println(key + " -- "+ value);

        }


// 4. Use put to insert a message with the code of 5 and the name of Li Xiaohong into the map set

map.put(5, "Li Xiaohong");


// 5. Use remove to remove the information No. 1 in the map

map.remove(1);


// 6. Use put to change the name information No. 2 in the map set to "Zhou Lin"

map.put(2, "Zhou Lin");

        System.out.println(map);

    }

}

Exercise 7: using Map sets (2)

  • There are two arrays, the first is: [Heilongjiang Province, Zhejiang Province, Jiangxi Province, Guangdong Province, Fujian Province], the second is: [Harbin, Hangzhou, Nanchang, Guangzhou, Fuzhou], the first array element is the key, the second array element is stored in the Map set as the value. For example, Heilongjiang Province = Harbin, Zhejiang Province = Hangzhou }.
public class MapTest05 {

public static void main(String[] args) {

// 1. Define the first array arr1

String[] arr1 = {"Heilongjiang Province", "Zhejiang Province", "Jiangxi Province", "Guangdong Province", "Fujian Province"};

// 2. Define the second array arr2

String[] arr2 = {"Harbin", "Hangzhou", "Nanchang", "Guangzhou", "Fuzhou"};


// 3. Create HashMap,key storage Province, value storage City

HashMap<String, String> hm = new HashMap<>();


// 4. Use normal for loop to traverse arr1

for (int i = 0; i < arr1.length; i++) {

// 5. Get the province in arr1 according to the index

String key = arr1[i];

// 6. Get the provincial capital city from arr2 according to the index

String value = arr2[i];


// 7. Add provinces and provincial capitals to the HashMap

hm.put(key, value);

        }

// 8. Output content in HashMap

System.out.println(hm);

    }

}

Exercise 8: using Map sets (3)

  • Define a List set whose generic type is String, and count the number of occurrences of each character (note, not String) in the set. For example, "a B C" and "B C D" are two elements in the set. The final output of the program is: "a = 1,b = 2,c = 2,d = 1".
public class MapTest06 {

public static void main(String[] args) {

// 1. Define the ArrayList storage element

ArrayList<String> arr = new ArrayList<String>();


// 2. Use the add method to add the required elements

arr.add("abc");

        arr.add("bcd");


// 3. Define a HashMap, where key is the character and value is the number of times corresponding to the character

HashMap<Character, Integer> hm = new HashMap<>();


// 4. Use enhanced for to get each string in ArrayList

for (String str : arr) {


// 5. Convert each string into a character array

char[] charArray = str.toCharArray();


// 6. Use enhanced for to traverse character array

for (char ch : charArray) {

// 7. Get each character and use the character to find the number of times in the HashMap

Integer num = hm.get(ch);

// 8. If it is empty, it means that the character appears for the first time

if (num == null) {

// 9. Put the character as the key and set the number of times to 1

hm.put(ch, 1);

                } else {

// 10. If there are already characters before, add the number of characters + 1

hm.put(ch, num + 1);

                }

            }

        }

// 11. Output the contents of map

System.out.println(hm);

    }

}