Created
July 23, 2021 03:42
-
-
Save truongkendy/fea22b4185b3ccf6ab270c498f2c0cef to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashMap; | |
import java.util.HashSet; | |
import java.util.Map; | |
import java.util.Objects; | |
import java.util.Set; | |
import java.util.stream.IntStream; | |
/** | |
* There is a Cat class with a String variable name, int variable age. | |
* | |
* Create a Map<Integer, Cat> and add 10 cats represented by (index, Cat) pairs. | |
* | |
* Get a Set of all cats from the Map and display it on the screen. | |
* | |
* Requirements | |
* •The program must not read data from the keyboard. | |
* •The createMap method must create a new HashMap<Integer, Cat> object. | |
* •The createMap method must add 10 cats to the map, represented by (index, Cat) pairs. | |
* •The createMap method must return the created map. | |
* •The convertMapToSet method must create and return the set of cats retrieved from the passed map. | |
* •The program must display name and age each cats in the set. | |
*/ | |
public class Task2 { | |
public static void main(String[] args) { | |
Task2 task = new Task2(); | |
Map<Integer, Cat> maps = task.createMap(); | |
Set<Cat> catSets = task.convertMapToSet(maps); | |
task.printCats(catSets); | |
} | |
public Map<Integer,Cat> createMap() { | |
Map<Integer, Cat> mapCats = new HashMap<>(); | |
IntStream.rangeClosed(1, 10).forEach(e -> { | |
String name = "cat " + e; | |
Cat cat = new Cat(name, e); | |
mapCats.put(e, cat); | |
});; | |
return mapCats; | |
} | |
public Set<Cat> convertMapToSet(Map<Integer, Cat> map){ | |
return new HashSet<>(map.values()); | |
} | |
public void printCats(Set<Cat> cats) { | |
cats.forEach(System.out::println); | |
} | |
public class Cat{ | |
private String name; | |
private int age; | |
public Cat(String name, int age) { | |
this.name = name; | |
this.age = age; | |
} | |
public String getName() { | |
return this.name; | |
} | |
public void setName(String name) { | |
this.name = name; | |
} | |
public int getAge() { | |
return this.age; | |
} | |
public void setAge(int age) { | |
this.age = age; | |
} | |
@Override | |
public String toString() { | |
return "{" + | |
" name='" + getName() + "'" + | |
", age='" + getAge() + "'" + | |
"}"; | |
} | |
@Override | |
public boolean equals(Object o) { | |
if (o == this) | |
return true; | |
if (!(o instanceof Cat)) { | |
return false; | |
} | |
Cat cat = (Cat) o; | |
return Objects.equals(name, cat.name) && age == cat.age; | |
} | |
@Override | |
public int hashCode() { | |
return Objects.hash(name, age); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment