Java - not adding to ArrayList of objects - java

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

Related

Add a new Key-Value to an existing HashMap

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

populate hashmap from hibernate query

public List<UMRDTO> getDocumentLink(Session session)
{
List<UMRDTO> documentationList = null;
Query query = null;
query = session.createQuery(UMRSQLInt.DOCUMENTATION_LIST);
documentationList = query.list();
return documentationList;
}
Whenever I restart my app all the hashmap are empty and no data is present that in inputed earlier
I need to get the list i.e objectName , objectType and the documentationLink from the above query and then put the data (objectName,documentationLink) in the HashMap if the objectName is Domainname then the data to be put in domainDocumentationMap or if it is combo then in domainComboDocumentationMap
private static Map<String, String> domainDocumentationMap = null;
private static Map<String, String> domainComboDocumentationMap = null;
static
{
domainDocumentationMap = new HashMap<String, String>();
domainComboDocumentationMap = new HashMap<String, String>();
}
public static Map<String, String> getDomainDocumentationMap(){
return domainDocumentationMap;
}
public static void setDomainDocumentationMap(String objectName, String documentationLink) {
MMTUtil.domainDocumentationMap.put(objectName, documentationLink);
}
what query shall i write?

Hibernate mapping of lists

I want to retrieve 3 columns from DB.More than 2 or 3 rows are retrieved while querying.This is the query String query="select createdTime,receiptStatus,pointsEarned from Receipt where loyaltyId=:loyaltyId";
List x= (List) entityManager.createQuery(query).setParameter("loyaltyId",loyaltyId).getResultList();
I want to map the columns to a pojo class and pass the list(or use an object of that pojo).i created a pojo class like this
public class TransactionHistoryEntity
{
private List<String> tranStatus;
private List<String> tranDate;
private List<String> pointsEarned;
public List<String> getTranStatus() {
return tranStatus;
}
public void setTranStatus(List<String> tranStatus) {
this.tranStatus = tranStatus;
}
public List<String> getTranDate() {
return tranDate;
}
public void setTranDate(List<String> tranDate) {
this.tranDate = tranDate;
}
public List<String> getPointsEarned() {
return pointsEarned;
}
public void setPointsEarned(List<String> pointsEarned) {
this.pointsEarned = pointsEarned;
}
}
created time should be mapped to tranDate,receiptstatus to tranStatus,pointsEarned to pointsEarned.
How can i achieve this ?? is my query correct ?
Criteria cr= getCurrentSession().createCriteria(Receipt.class)
.add(Restrictions.eq("loyaltyId", loyaltyId))
.setProjection(Projections.projectionList()
.add(Projections.property("createdTime"), "createdTime")
.add(Projections.property("receiptStatus"), "receiptStatus")
.add(Projections.property("pointsEarned "), "pointsEarned "))
.setResultTransformer(Transformers.aliasToBean(Receipt.class));
List<Receipt> receiptList = cr.list();
This Criteria act as String query="select createdTime,receiptStatus,pointsEarned from Receipt where loyaltyId=:loyaltyId"; and map the return result to List<Receipt>
TransactionHistoryEntity trans = new TransactionHistoryEntity ();
List<String> tranStatus = new ArrayList<String>();
List<String> tranDate = new ArrayList<String>();
List<String> pointsEarned = new ArrayList<String>();
for(int i = 0 ; i < receiptList.size() ; i++){
tranDate.add(receiptList.get(i).getCreatedTime());
tranStatus.add(receiptList.get(i).getReceiptStatus());
pointsEarned.add(receiptList.get(i).getPointsEarned());
}
TransactionHistoryEntity.setTranStatus(tranStatus);
TransactionHistoryEntity.setTranDate(tranDate);
TransactionHistoryEntity.setPointsEarned(pointsEarned)
And this to map the return result to TransactionHistoryEntity

Sorting a map in java

I have a tree map with a following key value pair combination
Map is declared as follows
Map<String, List<Bean>> outputMap = new TreeMap<String,List<Bean>>();
Corresponding code will be
for (String course_date : shiftSet) {
Bean courseBean = null;
boolean valueExists = false;
for (Entry<String, List<Bean>> entry: courseMap.entrySet()){
valueExists = false;
String studentDetail = entry.getKey();
String [] studentSet = StringUtils.getArray(studentDetail , ",");
String studentId = studentSet[0];
String courseId = studentSet[1];
for(Bean resultBean : entry.getValue()){
if(course_date.equalsIgnoreCase(resultBean.getCourseDate()){
valueExists = true;
}
}
if(!valueExists ) {
courseBean = new Bean();
courseBean.setStudent(studentId);
courseBean.setCourse(courseId);
List<Bean> courseList = entry.getValue();
courseList.add(courseBean);
outputMap.put(studentId+courseId, courseList);
}
}
}
And finally the OutputMap needs to be inserted to courseMap
OutputMap result will be
{ADV001,STU02=
[Bean[course_id=ADV1, student_id=STU1_2,Day=Wed-Night,courseDate=12-Feb-2014],
Bean[course_id=ADV1, student_id=STU1_2,Day=Tue-Day,courseDate=11-Feb-2014],
Bean[course_id=ADV1, student_id=STU1_2,Day=Tue-Night,courseDate=11-Feb-2014],
Bean[course_id=ADV1, student_id=STU1_2,Day=Wed-Day,courseDate=12-Feb-2014]]
So Here i need to sort the outputMap based on courseDate?Kindly help on how the desired output can be achieved ?
Thanks in advance..
A TreeMap sorts the elements by their key, if courseDate is part of the values, you'd have to use a TreeSet, e.g.
import java.util.Set;
import java.util.TreeSet;
public class Example {
public static void main(String[] args) {
Set<Dummy> example = new TreeSet<>();
example.add( new Dummy(7, "first dummy"));
example.add( new Dummy(2, "second dummy"));
example.add( new Dummy(3, "third dummy"));
System.out.println(example);
}
static class Dummy implements Comparable<Dummy>{
int courseDate;
String name;
Dummy(int courseDate, String name) {
this.courseDate = courseDate;
this.name = name;
}
#Override
public String toString() {
return String.format("[Dummy courseDate=%s, name=%s]", courseDate, name);
}
#Override
public int compareTo(Dummy o) {
// here you specify how the TreeSet will order your elements
return Integer.compare(this.courseDate, o.courseDate);
}
}
}

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".

Categories

Resources