Add a new Key-Value to an existing HashMap - java

I'm trying to add a new Key/Value to an existing HashMap (bandMap) where the second argument in my test() method must be of a Collection type.
As I'm still very new to Java so any help with an explanation would be appreciated.
import java.util.*;
public class Car
{
private Map<String, Set<String>> carMap = new HashMap<>(); //b
Set<String> model = new TreeSet<>();
/**
* Constructor for a Band object
*/
public void make()//b
{
Map<String, Set<String>> carMap = new HashMap<>();
}
/**
* Populate some sample data
*/
public void populate() //b
{
model.add("Fiesta");
model.add("Cougar");
model.add("Transit");
carMap.put("Ford", model);
model = new TreeSet<>();
model.add("Astra");
model.add("Calibra");
carMap.put("Vauxhall", model);
model = new TreeSet<>();
model.add("206");
model.add("106");
carMap.put("Peugeot", model);
}
/**
* I need a method to add a new key - value pair
*/
public void test(String makeName, Set<String> aModel)
{
//Code to add new Key/Value to the exisiting HashMap (carMap)
}
}

You just need the carMap as a class variable. And in your test() method (I renamed it addModel) simply use the put method as you do it in the populate method.
public class Car {
private Map<String, Set<String>> carMap = new HashMap<>();
/**
* Populate some sample data
*/
public void populate() {
Set<String> model = new TreeSet<>();
model.add("Fiesta");
model.add("Cougar");
model.add("Transit");
carMap.put("Ford", model);
model = new TreeSet<>();
model.add("Astra");
model.add("Calibra");
carMap.put("Vauxhall", model);
model = new TreeSet<>();
model.add("206");
model.add("106");
carMap.put("Peugeot", model);
}
public void addModel(String makeName, Set<String> aModel) {
carMap.put(makeName, aModel);
}
public Map<String, Set<String>> getCarMap() {
return carMap;
}
}
Then use it this way
public static void main(String[] args) {
Car car = new Car();
car.populate();
car.addModel("AnotherBrand", new HashSet<>(Arrays.asList("a", "b")));
System.out.println(car.getCarMap());
}
This outputs the following Map
{
Vauxhall=[Astra, Calibra],
Ford=[Cougar, Fiesta, Transit],
AnotherBrand=[a, b],
Peugeot=[106, 206]
}

Related

I have created a put() method for a SortedMap but can't seem to get test code to work

I just can't get this to work. Idea is to design a method that adds a Key Value pair to a Map, and although the program compiles correctly, test code of format " tracker.put("17/06/2019", "Jeffrey Burns"); " brings up error message
I've tried changing the method arguments to (String, List).
public class OfficeDeliveryTracker
private SortedMap<String, List<String>> deliveryTracker;
/**
* Constructor for objects of class OfficeDeliveryTracker
*/
public OfficeDeliveryTracker()
{
this.deliveryTracker = new TreeMap<>();
}
/**
* Adds key-value pair to the map
*/
public void addMapEntry(String key, String value)
{
List<String> list = deliveryTracker.get(key);
if (list == null) {
list = new ArrayList<String>();
}
list.add(value);
deliveryTracker.put(key, list);
}
I expect for the test code tracker.put("17/06/2019", "Jeffrey Burns"); to work, but instead get "Error: line 1 - cannot find symbol - method put(java.lang.String,java.lang.String)"
Check out below code:
As you are using SortedMap<String, List<String>> which takes String as key and list of String as value.
You can't use tracker.put("17/06/2019", "Jeffrey Burns") as "Jeffrey Burns" is String not List of String
public class OfficeDeliveryTracker {
private SortedMap<String, List<String>> deliveryTracker;
/**
* Constructor for objects of class OfficeDeliveryTracker
*/
public OfficeDeliveryTracker() {
this.deliveryTracker = new TreeMap<>();
}
/**
* Adds key-value pair to the map
*/
public void addMapEntry(String key, String value) {
List<String> list = deliveryTracker.get(key);
if (list == null) {
list = new ArrayList<String>();
}
list.add(value);
deliveryTracker.put(key, list);
}
public static void main(String[] args) {
OfficeDeliveryTracker tracker = new OfficeDeliveryTracker();
//tracker.put("17/06/2019", "Jeffrey Burns"); // Error : The method put(String, String) is undefined for the type OfficeDeliveryTracker;
tracker.addMapEntry("17/06/2019", "Jeffrey Burns");
}
}

Writing a method to add a String collection in a Map

So I have this data
Key Value
--- -----
fruit apple
fruit banana
fruit grapes
cars honda
cars lexus
cars bmw
schools harvard
schools yale
...
And I would like to construct the data to a Map<String, Collections<String>> and make a method that adds all the data. So far, I have a constructor that instantiates my Map variable
public Map<String, Collection<String>> keys;
public newMap() {
keys = new HashMap<>();
}
public void addkeys(String K, String V) {
Collection<String> names = new HashSet<String>();
if (keys.containsKey(K) && !keys.values().contains(V)) {
names.add(V);
courses.put(K, names);
} else if (!keys.containsKey(K) && !keys.values().contains(V)) {
names.add(V);
courses.put(student, classes);
}
}
So when I run my test
newMap.addkeys("fruit", "apple");
newMap.addkeys("fruit, "banana");
newMap.addkeys("fruit", "grapes");
newMap.addkeys("cars, "honda");
newMap.addkeys("cars", "lexus");
newMap.addkeys("cars, "bmw");
newMap.addkeys("schools", "harvard");
newMap.addkeys("schools, "yale");
it should return
fruit = [apple, banana, grapes]
cars = [honda, lexus, bmw]
schools = [hardvard, yale]
but instead I get
fruit = [grapes]
cars = [bmw]
schools = [yale]
it seems like it's only adding the last instance because whenever I call Collection<String> names = new HashSet<String>(), i'm re-instantiating names but when I this instantiation to the begininng of the class, It just adds on everything. So it returns fruit = [apple, banana, grapes, honda, lexus, bmw, hardvard, yale].
Pre-Java 8:
Use the fact that Map#get returns null when there is not a mapping in order to determine if you need to put a new collection in the map, then add the value to the collection.
public void addkeys(String K, String V) {
Collection<String> values = keys.get(K);
if (values == null) {
values = new HashSet<>();
keys.put(K, values);
}
values.add(V);
}
Java 8+:
Use Map#computeIfAbsent to add a new collection to the map if there is not a mapping, and then add the value to the returned collection.
public void addkeys(String K, String V) {
keys.computeIfAbsent(K, k -> new HashSet<>()).add(V);
}
You can rewrite your function like this:
public void addkeys(String K, String V) {
if (keys.containsKey(K)) {
keys.get(K).add(V); // add to existing hashset
} else {
Collection<String> names = new HashSet<String>();
names.add(V);
keys.put(K, names); // add new hashset for key
}
}
Try this
public Map<String, Set<String>> myMap;
public newMap() {
myMap = new HashMap<>();
}
public void putInMap(String key, String val) {
if (myMap.containsKey(key)) {
myMap.get(K).add(V);
} else {
Set<String> values = new HashSet<String>();
values.add(val);
myMap.put(key, values);
}
}

Java - not adding to ArrayList of objects

My code is not adding a new index to an ArrayList of object[]'s.
My code:
System.out.println("started1");
ArrayList<Object[]> toSend = new ArrayList<Object[]>();
System.out.println("started2");
for(Entry<String, Room> map : rooms.entrySet())
{
System.out.println("started3");
String key = map.getKey();
Room val = map.getValue();
System.out.println("started3.1");
Player owner = players.get(val.getOwnerID());
System.out.println("started3.125");
Object[] toAdd = new Object[] {key, val.getRoomName(), val.getCurrentPlayerSize(), val.getMaxPlayers(), owner.getName()};
System.out.println("started3.15");
toSend.add(toAdd);
System.out.println("started3.2");
}
System.out.println("started4");
client.sendEvent("refreshAvailableRooms", toSend);
System.out.println("started5");
It gets as far as setting the owner variable to link to a Player class. I have tried printing out the class values and they are all fine. It just stops when I try adding a new Object[] to my array of objects.
What could be going wrong? (In the console it stops printing after System.out.println(started3.125");
EDIT: I should mention that rooms (in the for loop) link to a HashMap:
private static HashMap<String, Player> players = new HashMap<String, Player>();
private static HashMap<String, Room> rooms = new HashMap<String, Room>();
EDIT2: RUNNABLE CODE
Room.java:
public class Room {
public String RoomName = "Room Name";
public int size = 3;
public int max = 10;
public String ownerID = "BobSmith";
public String ID = "Room1";
public Room() { }
}
Player.java:
public class Player {
public String ID = "BobSmith";
public String Name = "Bob";
public Player() { }
}
Main.java:
public class main {
private static HashMap<String, Player> players = new HashMap<String, Player>();
private static HashMap<String, Room> rooms = new HashMap<String, Room>();
public static void main(String args[]) {
players.put("BobSmith", new Player());
rooms.put("Room1", new Room());
rooms.put("Room2", new Room());
rooms.put("Room3", new Room());
System.out.println("started1");
ArrayList<Object[]> toSend = new ArrayList<Object[]>();
System.out.println("started2");
for(Entry<String, Room> map : rooms.entrySet())
{
System.out.println("started3");
String key = map.getKey();
Room val = map.getValue();
System.out.println("started3.1");
Player owner = players.get(val.ownerID);
System.out.println("started3.125");
Object[] toAdd = new Object[] {key, val.RoomName, val.size, val.max, owner.Name};
System.out.println("started3.15");
toSend.add(toAdd);
System.out.println("started3.2");
}
System.out.println("started4");
}
}

How to create deep table/list and insert/read data from/to it

I wanted to create a table/list in Java, and I wonder what is the best way to handle it.
The table should have a structure like this:
Term propertyList entitiesList
a1 p1=1, p2=2, p3=2 T1,T2
a2 p5=0, p4=5 ,p3=3 T2,T1
a3 p1=1 ,p4=3, p3=9 T3,T1,T2
...
a10
I have a list with exactly 10 terms, and for every term there is a list of properties (deep with key and value), and the properties can be either in one or more entities.
I need some help on how to create it, e.g. should I use list, map, collection etc.
How can I add hardcoded values to them as literals in the code, and what is the best way to read data from it, taking into account performance, given that later I will need to use this for every entity and find the related properties that participate in every term.
first off Create Term class.
So you have list of Terms: List<Term>
Term class
public class Term {
private String mName = "";
private Map<String, Integer> mPropertyMap = new LinkedHashMap<String, Integer>();
private List<String> mEntitiesList = new ArrayList<String>();
public Term(String name) {
mName = name;
}
public void generate(Map<String, Integer> propertyMap, List<String> entitiesList) {
mPropertyMap = propertyMap;
mEntitiesList = entitiesList;
}
public Map<String, Integer> getPropertyMap() {
return mPropertyMap;
}
public void setPropertyMap(Map<String, Integer> propertyMap) {
this.mPropertyMap = propertyMap;
}
public List<String> getEntitiesList() {
return mEntitiesList;
}
public void setEntitiesList(List<String> entitiesList) {
this.mEntitiesList = entitiesList;
}
public String getName() {
return mName;
}
public void setmName(String name) {
this.mName = name;
}
}
Main Class
public class MyClass {
private List<Term> mTermList = null;
private void init() {
mTermList = new ArrayList<Term>();
}
private void addSomeTerm() {
Map<String, Integer> propertyMap = new LinkedHashMap<String, Integer>();
propertyMap.put("p1", 1);
propertyMap.put("p2", 2);
propertyMap.put("p3", 3);
List<String> entitiesList = new ArrayList<String>();
entitiesList.add("T1");
entitiesList.add("T2");
Term term = new Term("a1");
term.generate(propertyMap, entitiesList);
mTermList.add(term);
}
private String printTerms() {
StringBuilder buff = new StringBuilder();
for(Term currTerm : mTermList){
buff.append(currTerm.getName()).append(" ");
Map<String, Integer> propertyMap = currTerm.getPropertyMap();
Set<String> sets = propertyMap.keySet();
Iterator<String> itr = sets.iterator();
String key = null;
Integer value = null;
while(itr.hasNext()){
key = itr.next();
value = propertyMap.get(key);
buff.append(key + "=" + value).append(",");
}
buff.setLength(buff.length()-1); // remove last ','
buff.append(" ");
List<String> entitiesList = currTerm.getEntitiesList();
for(String str : entitiesList){
buff.append(str).append(",");
}
buff.setLength(buff.length()-1); // remove last ','
}
return buff.toString();
}
/**
* #param args
*/
public static void main(String[] args) {
MyClass m = new MyClass();
m.init();
m.addSomeTerm();
System.out.println(m.printTerms());
}
}
Output:
a1 p1=1,p2=2,p3=3 T1,T2
It looks like you could have the following structure:
class Term {
String id;
Map<String, String> properties;
List<Entity> entities; // (or Set<Entity> if no duplicates are allowed)
}
But it's not very clear what you mean by "deep" and by "the properties can be either in one or more entities".

Populating hashmap from a hashset from an other class

I have a hashset in a class called myClass that contains 6 strings.
I want to be able to create a hashmap and use these 6 strings as keys in another class called Maps, and they values beside.
how can i call the hashmap from the map class and use the 6 Strings from the hashset in myClass.
public class MyFavouriteClasses {
Set<String> classes;
public MyFavouriteClasses() { }
public Set populate() {
Set<String> classes = new HashSet<String>();
classes = new HashSet<String>();
classes.add("ArrayList");
classes.add("Hashset");
classes.add("Random");
classes.add("AbstractList");
return classes;
}
}
public class MyFavoriteMapClass {
Map<String, String> map;
public MyFavoriteMapClass() { }
public void populate() {
MyFavouriteClasses class = new MyFavouriteClasses();
map = new HashMap<String, String>();
Set<String> classes = class.populate();
for(String str:classes) {
map.put(String, (Class)str.getPackage());
}
}
}

Categories

Resources