Creating a Hash Map of objects of a class - java

I want to create a hash map of objects of a class.
The class is as follows -
public class BitbucketRecordDataModel {
private String softwareId;
private String scmUrl;
private String aggregationDate;
public BitbucketRecordDataModel(String softwareId, String scmUrl, String aggregationDate) {
this.softwareId = softwareId;
this.scmUrl = scmUrl;
this.aggregationDate = aggregationDate;
}
public String getSoftwareId() {
return softwareId;
}
public void setSoftwareId(String softwareId) {
this.softwareId = softwareId;
}
public String getScmUrl() {
return scmUrl;
}
public void setScmUrl(String scmUrl) {
this.scmUrl = scmUrl;
}
public String getAggregationDate() {
return aggregationDate;
}
public void setAggregationDate(String aggregationDate) {
this.aggregationDate = aggregationDate;
}
}
I am creating a Hash map having key as String and trying to insert values into the hash map. But when I try to retrieve the details of the hash map, I get null and some very weird values which is the name of my class.
HashMap<String, BitbucketRecordDataModel> map = new HashMap<String, BitbucketRecordDataModel>();
cacheCondition = "hi";
username = "hi1";
protocol = "hi2";
BitbucketRecordDataModel bitbucketRecordDataModel = new BitbucketRecordDataModel(cacheCondition, username, protocol);
map.put(repoName, bitbucketRecordDataModel);
System.out.println(map.get("deployment-service-api.git"));
I am very new to Java and Hash Maps. What am I doing wrong and why I am getting such weird values?

First of all, you should override toString() method of Class. If you don't override it and call from any object instance, it responses as implementation of Object class. You can find the basic implementation of it here please find toString() Method
Please copy shared code block for toString() method below and paste it in the class.
Also i noticed that you define repoName as key while putting data to map but you use deployment-service-api.git as a key while retrieving the data.
Please be sure use the same key value.
#Override
public String toString() {
return "BitbucketRecordDataModel{" +
"softwareId='" + softwareId + '\'' +
", scmUrl='" + scmUrl + '\'' +
", aggregationDate='" + aggregationDate + '\'' +
'}';
}

Related

the contents of arraylist are printed using println. I want a similar functionality for my created objects without using toString() function in java

In the image above, the contents of the arraylist is printed using println. I want a similar functionality for my created objects without using toString() function in java
please tell me how can i do that
To facilitate the answer, I added a CustomClazz with toString method and two fields(firstField, secondField) to be printed. The code uses both the toString method and Stream-> println of each object;
import java.util.ArrayList;
import java.util.Arrays;
public class MyClass {
public static void main(String args[]) {
ArrayList<CustomClazz> list = new ArrayList<>();
list.add(new CustomClazz("custom1","class1"));
list.add(new CustomClazz("custom2","class2"));
list.add(new CustomClazz("custom3","class3"));
//Stream that accesses and concatenates each field of custom class.. notice the bad concatenation "+"
list.stream().map(customClass -> customClass.getFirstField()+ customClass.getSecondField()).forEach(System.out::println);
System.out.println();
System.out.println();
//Option that uses the toString method of customClazz.
System.out.println(Arrays.toString(list.toArray()));
}
}
class CustomClazz {
String firstField;
#Override
public String toString() {
return "CustomClazz{" +
"firstField='" + firstField + '\'' +
", secondField='" + secondField + '\'' +
'}';
}
String secondField;
public String getFirstField() {
return firstField;
}
public void setFirstField(String firstField) {
this.firstField = firstField;
}
public String getSecondField() {
return secondField;
}
public void setSecondField(String secondField) {
this.secondField = secondField;
}
public CustomClazz(String firstField, String secondField) {
super();
this.firstField = firstField;
this.secondField = secondField;
}
}

Trouble using HashMap containing Objects

Please pardon my bad English
I am trying to create a HashMap with a String as a key, and an Object as parameter, which I want to initialise each time the program runs so that its added to a new key in the HashMap.
The problem is, that not all values are returned, and namely the second, gives back a weird output.
package javaex1;
import java.util.*;
public class Javaex1 {
public static void main(String[] args) {
Person obj = new Person("Eminem", "Male");
HashMap<String, Person> MapPerson = new HashMap<String, Person>();
MapPerson.put("Eminem", obj);
System.out.println(MapPerson);
}
}
The object
package javaex1;
public class Person {
String Name;
String Gender;
public Person (String name, String Gend) {
this.Name = name;
this.Gender = Gend;
}
public String getName() {
return Name;
}
public String getGender() {
return Gender;
}
}
Any help or hint is greatly appreciated! Thank you in advance for your time!
The expected results should be "Eminem Male". Instead what I get is this:
{Eminem=javaex1.Person#2a139a55}
This happens because you are trying to print an Object, An Object when printed gives the default toString implementaion of Object class , which is shown below
// implementation of toString in Object class
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
This is what you can see in your current output .
You should ovverride toString method in Person class like this.
public String toString() {
return this.Name + " " + this.Gender;
}
So that it returns the name and gender
You should override toString method in Person class. Like that:
#Override
public String toString() {
return this.Name + " " + this.Gender;
}
You're printing the MapPerson object, not the Person one.
Your code should be:
Person person = MapPerson.get("Eminem");
System.out.println(person.getName() + " " + person.getGender());

HashMap Issuses

Edited the getTypeString method in the Flowers class now I just get the pointer to the object
I'm working on a project for one of my classes. I haven't worked with HashMap before and I need to use one. In this java class I'm trying to print out the full description that I have set. But it wont print the HashMap value from the key. I have tried to use some code from my book, but with no luck.
This is the class that is calling the class that has the HashMap:
public class Garden
{
private Gardener gardener;
private Tools tools;
private Flowers flowers;
/**
* Constructor for objects of class Garden
*/
public Garden()
{
gardener = new Gardener();
tools = new Tools();
Flowers rose;
rose = new Flowers("a beautiful red flower");
rose.setFlower("red", rose);
System.out.println(rose.fullDescription());
}
}
Edited the getTypeString method
This is the class that is using the HashMap:
import java.util.Set;
import java.util.HashMap;
public class Flowers
{
private String fDescription;
private HashMap<String, Flowers> flowers;
/**
* Constructor for objects of class Flowers
*/
public Flowers(String fDescription)
{
this.fDescription = fDescription;
flowers = new HashMap<String, Flowers>();
}
public void setFlower(String color, Flowers type)
{
flowers.put(color, type);
}
public String flowerDescription()
{
return fDescription;
}
public String fullDescription()
{
return "The "+ getTypeString() + " is " + fDescription;
}
private String getTypeString()
{
String des = "";
Collection<Flowers> vals = flowers.values();
for(Flowers f : vals){
des += f;
}
return des;
}
}
The problem, I think, is in the getTypeString() function. Can anyone point me in the right direction?
Edit
I removed the getTypeString method and edited the fullDescription method:
public String fullDescription()
{
return "The "+ type + " is " + fDescription;
}
now I'm trying to get the 'HashMap' to print the objects like so:
"Flower [type= type, description= Description "]"
using thes methods:
public static void printHashMap()
{
System.out.println("hashmap: " + flowers);
}
#Override
public String toString()
{
return "Flower [type=" + type + ", description=" + fDescription ]";
}
From your post, what I have understood is that you want to print the description of flowers. So I think you can try something like:
private String getTypeString(){
String des = "";
Collection<String> vals = flowers.values();
for(String f : vals){
des = des + f.flowerDescription();
}
return des;
}
Override the toString method in your class
Declare a toString method with the following modifiers and return type:
#Override
public String toString() {
return this.fDescription;
}
Implement the method so that it returns a string.

Final print statement returning null (java)

I have a basic name application that is taking in user data from the main class, splits the data in the parser class and then tries to assign everything in the final class and print it out in the toString method. I know the main class and the parser are working fine. I have verified in the parser class that the data DOES split properly and also sends the data through the object I made to the final class to assign it all. However, my final code is returning null..
MAIN CLASS
import java.util.Scanner;
public class MainClass {
public static void main (String[]args)
{
Scanner input = new Scanner(System.in); //create scanner object to gather name information
String fullName = null; //set the predefined value for the users name to null
nameParse splitInformation = new nameParse(); //method build to split the name into different sections
SecondClass access = new SecondClass(); //class built to output the different name data
System.out.println("What is your name?");
fullName = input.nextLine(); //store the users name and pass it into the data parser
splitInformation.parseNameInformation(fullName); //name parsing parameters built
System.out.println(access.toString());
}
}
Data Parser Class
public class nameParse {
private String firstName;
private String middleName;
private String lastName;
public nameParse()
{
firstName = "initial";
middleName = "initial";
lastName = "initial";
}
public void parseNameInformation(String inputInfo)
{
//Create an array to store the data and split it into multiple sectors
String nameInformation[] = inputInfo.split("\\s");
firstName = nameInformation[0];
middleName = nameInformation[1];
lastName = nameInformation[2];
//System.out.println(firstName + " " + middleName + " " + lastName);
SecondClass sendData = new SecondClass();
sendData.setFirstName(firstName);
sendData.setMiddleName(middleName);
sendData.setLastName(lastName);
}
}
Final Class
__
public class SecondClass {
private String firstName;
private String middleName;
private String lastName;
/*public String GFN()
{
return firstName;
}
public String GMN()
{
return middleName;
}
public String GLN()
{
return lastName;
}*/
public String setFirstName(String yourFirstName)
{
firstName = yourFirstName;
return this.firstName;
}
public String setMiddleName(String yourMiddleName)
{
middleName = yourMiddleName;
return this.middleName;
}
public String setLastName(String yourLastName)
{
lastName = yourLastName;
return this.lastName;
}
public String getFN()
{
return firstName;
}
public String toString()
{
String printNameInfo = "\nYour First Name:\t" + getFN();
return printNameInfo;
}
}
You never set any of your SecondClass object's (called "access") fields, so of course they'll all be null.
So in short, your code creates a nameParse object, gets information from the user, but does nothing with that information. You create a SecondClass object called access, put no data into it, and so should expect no valid data in it when you try to print it out. Solution: put information into your SecondClass object first. Call its setter methods:
// be sure to call the setter methods before trying to print anything out:
access.setSomething(something);
access.setSomethingElse(somethingElse);
Edit
You state:
I thought I set the data using the sendData.setFirstname(...) etc?
In the parseNameInformation method you create a new SecondClass object and you do set the fields of this object, but this object is completely distinct from the one in your main method whose fields are still null. To solve this, give parseNameInformation a method parameter and pass in your main method's SecondClass object into it and set its methods. You'll have to create the SecondClass object before calling the method of course.
i.e.,
public void parseNameInformation(String inputInfo, SecondClass sendData)
{
//Create an array to store the data and split it into multiple sectors
String nameInformation[] = inputInfo.split("\\s");
firstName = nameInformation[0];
middleName = nameInformation[1];
lastName = nameInformation[2];
//System.out.println(firstName + " " + middleName + " " + lastName);
// SecondClass sendData = new SecondClass(); // !!! get rid of this
sendData.setFirstName(firstName);
sendData.setMiddleName(middleName);
sendData.setLastName(lastName);
}

How To Pass a JRBeanCollectionDataSource to iReport?

I'm currently trying to use jasper to help me create reports. I have the information and data that I want displayed in this method:
private void writeToFile(final List<ScenarioLoadModel> sceneLoadModel) throws Exception {
final BufferedWriter bw = new BufferedWriter(new FileWriter("/Uma/nft/result.psv"));
for (final ScenarioLoadModel slm : sceneLoadModel) {
bw.write(slm.getScenarioId() + PSP + slm.getScenarioId() + PSP + slm.getScenarioConfig().getName() + PSP + slm.getLoad() + PSP + "" + EOL);
if (!slm.getScenarios().isEmpty()) {
final int tempCount = slm.getScenarios().get(0).getTemplates().size();
final int sceneCount = slm.getScenarios().size();
for (int tempIdx = 0; tempIdx < tempCount; tempIdx++) {
String id = null;
int pass = 0;
int fail = 0;
final Map<String, BigDecimal> metricMap = new HashMap<String, BigDecimal>();
final DefaultStatisticalCategoryDataset dataset = new DefaultStatisticalCategoryDataset();
for (int sceneIdx = 0; sceneIdx < sceneCount; sceneIdx++) {
final Template temp = slm.getScenarios().get(sceneIdx).getTemplates().get(tempIdx);
if (temp.isError()) {
fail++;
} else {
pass++;
}
if (sceneIdx == 0) {
id = temp.getId();
}
final MetricGroupModel mgm = slm.getScenarios().get(sceneIdx).getMetricGroupModel().get(tempIdx);
if (mgm != null) {
for (final MetricModel mm : mgm.getMetricModel()) {
for (final MetricValue mv : mm.getMetricValue()) {
dataset.add(mv.getValue(), new BigDecimal(0.0), mv.getType(), id);
}
}
}
}
final TemplateConfig tc = TemplateManager.getTemplateConfig(id);
bw.write(slm.getScenarioId() + PSP);
bw.write(id + PSP + tc.getName() + PSP + 1 + PSP + pass + "/" + fail);
for (final Object row : dataset.getRowKeys()) {
final Number mean = dataset.getValue((String) row, id);
bw.write(PSP + row + PSP + mean);
}
bw.write(EOL);
}
}
}
bw.close();
}
From my understanding I create Beans and then put them all in a Bean Factory, to create my object that will be ready to be passed to iReport.
How can I put all this information into a Bean? I essentially want the bean to include the scenario/test case and whether or not it passed. (This is for test automation)
I tried to read your code to make a a best guess at what columns you would want, but with no context, I have no clue. All the bean is a pojo, with private fields and public getters and setters.
Assuming there is no grouping and essentially each ScenarioLoadModel will correspond to one row in the report you would end up with a bean like this:
public class ScenariaResults {
private String id;
private String name;
private String load;
private int passCount;
private int failCount;
public ScenariaResults(String id, String name, String load, int passCount,
int failCount) {
super();
this.id = id;
this.name = name;
this.load = load;
this.passCount = passCount;
this.failCount = failCount;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLoad() {
return load;
}
public void setLoad(String load) {
this.load = load;
}
public int getPassCount() {
return passCount;
}
public void setPassCount(int passCount) {
this.passCount = passCount;
}
public int getFailCount() {
return failCount;
}
public void setFailCount(int failCount) {
this.failCount = failCount;
}
#Override
public String toString() {
return "ScenariaResults [id=" + id + ", name=" + name + ", load="
+ load + ", passCount=" + passCount + ", failCount="
+ failCount + "]";
}
}
So basically in the code you have above you build instances of ScenarioResults and add them to a list. Once you have the list, all you need to do is create a JRDataSource:
List<ScenarioResults> dataBeanList = ...call your method to get the list of results
//create the datasource
JRDataSource dataSource = new JRBeanCollectionDataSource(dataBeanList);
Now when designing the report in iReport it can be a little tricky to get the fields imported automatically. Basically first add your project with the bean to the classpath in iReports (could just point it to the bin folder or jar file`): Tools -> options -> classpath tab. Now follow these steps to add the fields.
Click the following icon:
Select the JavaBean Datasource tab.
Enter the classname of your bean. (ex. ScenarioResults)
Click Read attributes
Highlight the fields you want in the report and click Add Selected Field(s).
Click OK.
Now if you want to test what the report looks like with data, and not just an empty datasource, this is where the Factory comes in. It is only for testing while using iReport. You need to create a class that will essentially create a dummy data set for you. It should look something like:
import java.util.ArrayList;
import java.util.List;
public class ScenarioResultsFactory {
public static List<ScenarioResults> createBeanCollection() {
List<ScenarioResults> list = new ArrayList<ScenarioResults>();
list.add(new ScenarioResults("1", "test", "load", 10, 5));
//add as many as you want
return list;
}
}
Now you need to create a Datasource pointing to it in iReport.
Next to the Datasource dropdown in the toolbar click the icon with the tooltip `Report Datasources.
Click New.
Select JavaBeans set datasource. Click Next.
For name enter ScenarioResultsFactory.
For the Factory class you need to put the classname including package. So if the class is in the com package you should have com.ScenarioResultsFactory here.
For the static method put createBeanCollection if not already there.
Check the Use field description check box. Click Test to make sure it worked.
Click Save.

Categories

Resources