java output List with toString - java

My class having field is List<>, I went output tostring method
private String subjectCode;
private Long clientSn;
private Long ruleId;
private String beginDate;
private List<LessonPreferenceItemDTO> classPlans;
#Override
public String toString() {
return "LessonPreferenceSaveReqDTO{" +
"subjectCode='" + subjectCode + '\'' +
", clientSn=" + clientSn +
", ruleId=" + ruleId +
", beginDate='" + beginDate + '\'' +
", classPlans=" + classPlans +
'}';
}
But, classPlans outout is java entity,don't LessonPreferenceItemDTO field info,So,How was output classPlans in this toString()

You have to override public String toString() for LessonPreferenceItemDTO as well. You may give Apache Commons
ToStringBuilder.reflectionToString a try if you like to output every property.
The class ArrayList for instance will render itself by surrounding its elements with { and } and separating the elements contained by , calling toString() of each contained element.
If you don't like the resulting format of List.toString() you have to serialize the list by yourself while iterating over each element.

You have to override toString() method in LessonPreferenceItemDTO class but that's not all after that you need to call toString() on each element of this list.
You can use Java 8 stream API for that
classPlans.stream()
.map(LessonPreferenceItemDTO::toString)
.collect(Collectors.joining(","));

#Override
public String toString() {
return "LessonPreferenceSaveReqDTO{" +
"subjectCode='" + subjectCode + '\'' +
", clientSn=" + clientSn +
", ruleId=" + ruleId +
", beginDate='" + beginDate + '\'' +
", classPlans=" + classPlans.stream().map(LessonPreferenceItemDTO::toString).collect(Collectors.joining(",")) +
'}';
}
I success output wants,use java 8 stream,very thanks#Harmlezz#Neeraj Jain

Related

I dont understand a problem im having with an toString while mixing it with my UI

I have a SuperClass and two subclasses.
This two subclasses are used on my ui when i click on a button. I want to create one Estudiante and put it on a list. Estudiante has a lot of attributes inside it so i have toString methods on the subclasses and on the superclass.
I have edited the properties of the setListData so a string is no longer required. The problem is, now when i run the program and i try to add an Estudiante and show it, it gives me the StackOverflowError on the lines of the toString of the subclass and the superclass. I would really appreaciate if someone could try to fix it with my code. Thanks
I havent tried much, i have only changed the method for setting the list in the past but now theorically its fixed.
public class Estudiante extends Persona{
private int numero;
private int semestre;
public Estudiante(String unNombre, int unaCedula, String unMail, int unNumero, int unSemestre) {
super(unNombre,unaCedula,unMail);
this.setNumero(unNumero);
this.setSemestre(unSemestre);
}
The toString() of Estudiante (I didnt posted the get and set methods because i dont think they mattered)
#Override
public String toString(){
return super.toString() + "Numero:" + this.getNumero() + "Semestre: " + this.getSemestre();
}
```
SUPERCLASS TOSTRING (Persona)
#Override
public String toString(){
return toString() + "Nombre"+ this.getNombre() + "Cedula " + this.getCedula() + "Mail " + this.getMail();
}
public Persona(String unNombre, int unaCedula, String unMail){
this.setNombre(unNombre);
this.setCedula(unaCedula);
this.setMail(unMail);
}
This is what i have on the UI
private void BotonCrearEstudianteActionPerformed(java.awt.event.ActionEvent evt) {
Estudiante unEst=new Estudiante(NombreEstudiante.getText(), Integer.parseInt(CedulaEstudiante.getText()),MailEstudiante.getText(), Integer.parseInt(NumeroEstudiante.getText()), Integer.parseInt(SemestreEstudiante.getText()));
modelo.agregarEstudiante(unEst);
ListaEstudiantesJ.setListData(modelo.getListaEstudiantes().toArray());
StackOverflowError on the lines of both toStrings, the one on the subclass and the one in the superclass.
This
public String toString(){
return toString()
+ "Nombre"+ getNombre() + "Cedula " + getCedula() + "Mail " + getMail();
}
calls the overriden toString:
public String toString(){
return super.toString()
+ "Numero:" + getNumero() + "Semestre: " + getSemestre();
}
which again calls the original toString.
Hence and endless loop.
In the base class there are two possiblities:
Only super.toString() is correct:
public String toString(){
return super.toString()
+ "Nombre"+ getNombre() + "Cedula " + getCedula() + "Mail " + getMail();
}
Or simply no toString at all.
public String toString(){
return "Nombre"+ getNombre() + "Cedula " + getCedula() + "Mail " + getMail();
}

disassemble object in array

I have a search method in the database that brings me the following result:
As you see that inside the Object [4] comes another array containing People, Pessoas, and PessoasEnderecos and more objects that have relantionship with Pessoas.
I would like it to return only this way and not inside another array as it is happening now, it should look like this:
elementData=Object[10](id=144)
[0]=Pessoas(id=166)
[1]=PessoasEnderecos(id=167)
...
i have this method:
#RequestMapping(method = RequestMethod.GET, value = "/pessoas")
public ResponseEntity<Collection<Pessoas>> buscarPessoas(HttpServletRequest request) throws Exception {
String idEntidadeCrypt = request.getHeader("DataBase");
Long idEntidade = Long.parseLong(Crypto.decode(idEntidadeCrypt));
Collection<Pessoas> pessoasBuscados = pessoasService.buscarFiltro(idEntidade);
return new ResponseEntity<>(pessoasBuscados, HttpStatus.OK);
}
and :
#Repository
public interface PessoasRepository extends JpaRepository<Pessoas, Integer> {
#Query( value="select pes, pEnd, pFis, pJur "
+ "from "
+ "Pessoas pes, "
+ "PessoasEnderecos pEnd,"
+ "PessoasFisicas pFis,"
+ "PessoasJuridicas pJur"
+ " where "
+ "pes.entidade.idEntidade = pEnd.entidade.idEntidade "
+ "and pes.idPessoa = pEnd.pessoa.idPessoa "
+ "and pes.entidade.idEntidade = pFis.entidade.idEntidade "
+ "and pes.idPessoa = pFis.pessoa.idPessoa "
+ "and pes.entidade.idEntidade = pJur.entidade.idEntidade "
+ "and pes.idPessoa = pJur.pessoa.idPessoa "
+ "and pes.entidade.idEntidade = :parametroId " )
public Collection<Pessoas> encontrar(#Param("parametroId") Long usuarioEntidade);
how can i solve that ?
ArrayList<> does not work with magic, it has an actual implementation. elementData is the array where it stores its elements. As you can see (that is a link in the previous sentence), it is a private member of the class, so you do not interact with it, but you see it in a debugger because it exists.
If you want to return an array instead of a List, you can always use toArray() which all Lists implement.

Univocity Parsers: Calling a function from here is not working: parserSettings.selectFields( *some_function* );

I am using a .csv file and would like to pass a string constructed by a function to: parserSettings.selectFields( function );
During testing, when the string returned by the function is pasted directly into: parserSettings.selectFields( string ); the parsing works fine, however, when the function is used instead, the parse doesn't work, and there is only output of whitespace.
Here is the function:
public String buildColList() {
//Parse the qty col names string, which is a comma separated string
String qtyString = getQtyString();
List<String> qtyCols = Arrays.asList(qtyString.split("\\s*,\\s*"));
String colString = StringUtils.join(qtyCols.toArray(), "\"" + ", " + "\"");
String fullColString;
fullColString = "\"" + getString1() + "\"" + ", " + "\"" + getString2() + "\"" + ", " + "\"" + colString + "\"" + ", " + "\"" + getString4 + "\"";
return fullColString;
}
Here is how it is placed:
parserSettings.selectFields(buildColList());
Any help would be greatly appreciated, thanks.
You need to return an array from your buildColList method, as the parserSettings.selectFields() method won't split a single string. Your current implementation is selecting a single, big header instead of multiple columns. Change your method to do something like this:
public String[] buildColList() {
//Parse the qty col names string, which is a comma separated string
String qtyString = getQtyString();
List<String> qtyCols = Arrays.asList(qtyString.split("\\s*,\\s*"));
String colString = StringUtils.join(qtyCols.toArray(), "\"" + ", " + "\"");
String[] fullColString = new String[]{getString1(), getString2(), colString, getString4};
return fullColString;
}
And it should work. You might need to adjust my solution to fit your particular scenario as I didn't run this code. Also, I'm not sure why you were appending quotes around the column names, so I removed them.
Hope this helps.

How to grab data from a class without making it static per say [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
So for example I have this class that outputs my detailed flight output that is in the java doc "Flight.java" :
public String toDetailedString() {
String output =
getDeparture() + " - " + getArrival() + "\n" + Airport.getAirportCity(source) + " (" +
source + ") - " + Airport.getAirportCity(destination) + " (" + destination + ")" +
"\n" + plane.getAirline() + " " + number + " * " + plane.getModel();
return output;
}
and I have an Itinerary class "Itinerary.java" and I want to pull the info from Flight.java without making toDetailedString static, is that possible?
For added info, each of the variables you see "source, number, destination" are all private variables in Flight.java which I know are enclosed encapsulation. Any help is greatly valuable.
Example implementation in Itinerary.java
public String toString() {
return "The total cost is" + getTotalCost() + Flight.toDetailedString();
}
UPDATE:
In my Flight constructor I have:
public Flight(Plane plane, String number, double cost, Time departure, int duration, Airport source, Airport destination) {
this.plane = plane;
this.number = number;
this.cost = cost;
this.departure = departure;
this.duration = duration;
this.source = source;
this.destination = destination;
}
In which I created the object "f1" in my ItineraryTest class:
Flight f1 = new Flight(new Plane(Airline.American, "Airbus A321"),
"495",
79,
new Time(7, 10), 100,
Airport.PHX, Airport.LAX);
Thus I linked my object to the toDetailedString() the object "f1" was renamed to "first" in my Itinerary.java and a second object was created called "f2" and moved to "second" (to avoid confusion) :
public String toString() {
return "The total cost: "
+ getTotalCost()
+ " "
+ first.toDetailedString()
+ second.toDetailedString();
}
I thought I answered my own question, but now receive an error of:
Exception in thread "main" java.lang.NullPointerException at
Itinerary.toString(Itinerary.java:117) at
java.lang.String.valueOf(String.java:2994) at
java.io.PrintStream.println(PrintStream.java:821) at
ItineraryTest.main(ItineraryTest.java:20)
Possible, clean option is creating another class named FlightToDetailedString, with (possibly static) method toDetailedString. That method would accept instance of Flight as parameter
class FlightToDetailedString {
public String toDetailedString(Flight flight) {
String output =
getDeparture() + " - " + getArrival() + "\n" + Airport.getAirportCity(source) + " (" +
source + ") - " + Airport.getAirportCity(destination) + " (" + destination + ")" +
"\n" + plane.getAirline() + " " + number + " * " + plane.getModel();
return output;
}
}
In my example method is not static. With non-static member mehod, FlightToDetailedString could have (and use in toDetailedString) fields of FlightToDetailedString class. For example, Airport could be member variable of FlightToDetailedString. Are you sure you want to limit yourself to one airport?
Why you do not like toDetailedString as non-static member of Flight class in first place? In example you give it is most natural solution. if your Itinerary needs to access details of Flight class, just pass instance of Flight object as argument!
The consumer of toDetailedString() doesn't need access to anything inside Flight.
Your NullPointerException is likely caused by one of the fields in the Flight instance being null.
Finally, consider using a StringBuilder instead of concatenating strings.

Properly using toString to print array? [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 6 years ago.
I have an array that I need to print, and I've already looked through stackoverflow so I know that I need to use toString so that I don't just print the hashcode, but for some reason it's still printing stuff like "music2.Music2#4162b8ce, music2.Music2#3852fdeb, music2.Music2#509c6c30"
Music2[] musiclist = new Music2[10];
musiclist[0] = new Music2("Pieces of You", "1994", "Jewel");
musiclist[1] = new Music2("Jagged Little Pill", "1995", "Alanis Morissette");
musiclist[2] = new Music2("What If It's You", "1995", "Reba McEntire");
musiclist[3] = new Music2("Misunderstood", "2001", "Pink");
musiclist[4] = new Music2("Laundry Service", "2001", "Shakira");
musiclist[5] = new Music2("Taking the Long Way", "2006", "Dixie Chicks");
musiclist[6] = new Music2("Under My Skin", "2004", "Avril Lavigne");
musiclist[7] = new Music2("Let Go", "2002", "Avril Lavigne");
musiclist[8] = new Music2("Let It Go", "2007", "Tim McGraw");
musiclist[9] = new Music2("White Flag", "2004", "Dido");
public static void printMusic(Music2[] musiclist) {
System.out.println(Arrays.toString(musiclist));
}
This is my array and the method that I am using to print it. Any help would be appreciated.
You should define toString() method in your Music2 class and print it in the way you like. I don't know how fields in your object are named exactly, but it can look like this:
public class Music2 {
...
#Override
public String toString() {
return this.artist + " - "+ this.title + " (" + this.year + ")";
}
}
After that your printMusic method will work as expected.
You can declare a for each loop to display the property of music. This is the code
for (Music2 music : musiclist){
System.out.println("Title: " + music.getTitle);
}
Because by default Arrays got toString() implementation of the Object class, that is:
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
So you need to overwrite toString() in your Class
#Override
public String toString() {
return this.fieldNameone + " "+ this.fieldNametwo + " " + this.fieldNamethree + " ";
}
If using Java8 you can use
Arrays.stream(musiclist).forEach(System.out::print)
but make sure that Music2 has an overriden method for toString()
In the Arrays.toString(musiclist) you are actually invoking toString() on each element of the array to compose the resulting string. So, if you override the basic Object toString() implementation in Music2 class you will get what you want
public class Music2 {
.....
#Override
public String toString() {
return "Music2{" + "title=" + title + ", group=" + group + ", year=" + year + '}';
}
}

Categories

Resources