I have a properties inside the DVDs object called releaseDate and its a String.
getReleaseDateFormatted() is a method inside my DVDs object where I would parse a String to LocalDate.
I assume the following code would group all the releaseDate together in LocalDate type? I need to find the latest date inside this group.
#Override
public DVDs getOldestDVD() throws PersistenceException {
return dvdMap.values()
.stream()
.collect(Collectors.groupingBy(d -> d getReleaseDateFormatted()))
}
The question is very vague and confusing, but if my understanding is correct, you shouldn't need any streams. Try this:
return Collections.max(dvdMap.values(),
Comparator.comparing(DVDs::getReleaseDateFormatted));
Related
In here, I'm receiving a NullPointerException problem which seems to be related to my Date object in my class, but I can't figure it out.
My teacher said that everything works except that I'm returning the wrong data types for my date class, but I KNOW I'm returning a string, after all, that is what a getDate() method returns
I've tried putting in the code for the getDate() method itself, as in
"getMonth() + "/" + getDay() + "/" + getYear();
//main employee class
public class Employee
{
//2 attribute for employee
private String name;
private Date dateHired;
public boolean employeeType; //to check what type of employee, if
//false, then employee is salaried, otherwise hourly
//setter methods
public void setDateHired(int m, int d, int y)
{
Date dateHired = new Date(m,d,y);
}
public void setName(String s)
{
name = s;
}
public void setHoursWorked(int w)
{
}
//getter methods
protected String getDateHired()
{
return dateHired.getDate();
}
There isn't supposed to be an error, I reviewed this code hundreds of times and everything seems to be fine!
public void setDateHired(int m, int d, int y)
{
//dateHired is a local variable.. you're not modifying the class instance variable.
Date dateHired = new Date(m,d,y);
}
should be:
public void setDateHired(int m, int d, int y)
{
this.dateHired = new Date(m,d,y);
//or:
//dateHired = new Date(m,d,y);
}
Before turning to your actual questions, you have
private Date dateHired;
I recommend you don’t use the Date class. It was always poorly designed and is now long outdated. Despite its name it also doesn’t represent a date, but a moment in time at which there are two or three different dates around the globe. Instead use LocalDate from java.time, the modern Java date and time API. Use the tutorial link at the bottom.
For the NullPointerException Brandon has already explained how that came about from the following line:
Date dateHired = new Date(m,d,y);
Using LocalDate the line should be:
dateHired = LocalDate.of(y, m, d);
In new Date(m,d,y) you have got the arguments in the wrong order, you are treating year and month incorrectly and you are using a constructor that has been deprecated for decades, never ever do that.
My teacher said that everything works except that I'm returning the
wrong data types for my date class, but I KNOW I'm returning a string,
after all, that is what a getDate() method returns
The getDate method has been deprecated just as long, don’t use that one either. It also doesn’t give you the full date, and your teacher is correct, it doesn’t return a string, it returns an int.
I've tried putting in the code for the getDate() method itself, as in
getMonth() + "/" + getDay() + "/" + getYear();
You’d be surprised. However, rather than getting surprised and confused use a formatter for formatting your LocalDate into a string.
protected String getDateHired()
{
DateTimeFormatter dateFormatter
= DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
return dateHired.format(dateFormatter);
}
Example output from this method assuming US locale and a hire date of December 1, 2018:
12/1/18
ofLocalizedDate gives you a formatter for the default locale, so if your locale differs from US, you may be pleasantly surprised that the format of the string matches your expectations better than the quoted example. Normally one would declare the formatter a constant (a static final variable in the class), but I wasn’t sure that you had learned about this yet, so in this case I didn’t.
Long story short: Using the outdated Date class correctly is a lot harder than you would think because of its poor design. Don’t struggle with that one. Use of the modern LocalDate comes a lot more naturally. It numbers years and months the same way as humans do (at least since year 1 AD) and its method names are clearer, just mention a few of the many advantages.
Tutorial link: Oracle tutorial: Date Time explaining how to use java.time.
Get / Set methods are there to protect my class fields.
But since Java is working with reference my private fields are still getting exposed..
e.g.
private Date d;
Date getDate(){
return d;
}
void setDate(Date inD){
//Checks for inD
d = inD;
}
//Still the issue is
getDate().setHours(xyz);
What is the correct approach? Because i dont want to change my Date without using setDate.
Because i dont want to change my Date without using setDate.
Then you shouldn't return a reference to a mutable object in your get method. For example:
private Date d;
Date getDate() {
// Return a reference to an independent copy of the original data
return new Date(d.getTime());
}
void setDate(Date inD) {
// Checks for inD
d = inD;
}
A better approach (IMO) would be to use immutable types for your fields - the Joda Time API is a much cleaner date/time library and it has plenty of immutable types.
Now that was just an example of course - in other cases you might want to return an immutable view on a mutable object (which you would usually avoid mutating yourself) in order to avoid having to copy a lot of data on each get call.
There is a good approach for that which is called Defensive Copy,
Date getDate(){
return new Date(d.getTime());
}
you'll get a copy of it and original one will have no affect
Date is just an abomination since it is mutable. What you could do to make it safe, is to return a copy of the date. If that is modified, the original value is not changed.
i'm new with Play Framework and I want to checks my forms.
I currently try to create a custom formatter for Dates. When I receive a field called "startTimestamp", I want it to pass by my custom formatter which will transform it into a Java date.
This is my code :
public static Result create() {
Formatters.register(Date.class, new Formatters.SimpleFormatter<Date>(){
#Override
public Date parse(String timestamp, Locale arg1) throws ParseException {
return new Date(Long.parseLong(timestamp));
}
#Override
public String print(Date arg0, Locale arg1) {
// TODO Auto-generated method stub
return null;
}
});
// controller code
}
I don't understand how it could possibly work. How could i say to my formatter that a special String field called "startTimestamp" need to be formatted, but my others string fields don't need it ?
At the beginning I wanted to bind my object with some others objects but the bind method from play forms accepts only Strings. If there is a solution for this I could be interested too !
Am I clear ? I don't speak a very great english so it could be a little confuse for you ^^
Thanks you all.
this will work since play know to convert between a map and an object that have the same attribute names
in addition you on your template you specify the Object that is mapped to this form
using the two together is enough for play to infer the type of the field being converted
you can't bind other type then string because the conversion is done between the Web Page (Http format) and the Java Language. Http doesn't have object only strings
I don't speak a very great English either
you could register the formatter on the Global.Onstart
I'd like know how do to a method return a JSON array of List, for example:
#GET
#Produces("application/json")
public List<String> aMethod(){
return Array.asList("text1", "text2", "text3");
}
I'd want to know, how do to receive a List argument type in my method, for example
#PUT
#Consumes("application/json") void otherMethod(List<String>){
// do something ;
}
I've read about JaxbContext, I understanding how it can help me.
With JAXB there are two type's of List supported. The first is a List of elements, the second a delimited string (a "normal" XML value or attribute, which is parsed into a list using some delimiter). The first seems to be what you want ("array").
For reference, see: http://jaxb.java.net/jaxb20-ed/api/javax/xml/bind/annotation/XmlList.html
You will note that in both cases the List you want would need to be encapsulated by some other object. Fundamentally, XML (and by extension JAXB) likes to trace everything back to a single root node/object. So to model it, you need something like this:
#XmlRootElement(name="wrapper")
public abstract class ListWrapper {
public List<String> names;
}
Then your methods would need to be changed to accept/return ListWrapper objects and extract the actual List from it.
I tried the same without success, so I ended with packing a string into one field object.
return listWithString
.stream()
.map(
stringElement -> {
MyBoxObject bo = new MyBoxObject();
bo.setSomeField(stringElement);
return bo;
})
.collect(Collectors.toList());
I have Date in this format 2009-09-17T00:00:00.000-35:00 . As per the business Rules for my Application , i have written 3 Methods which will accept this Date and returns the Date in MM/yyyy , yyyyMM and dd .
For example one method is shown below MM/yyyy
private String getMonthYear(String date) throws Exception {
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
String s1 = date;
String s2 = null;
Date d;
try {
d = sdf.parse(s1);
s2 = (new SimpleDateFormat("MM/yyyy")).format(d);
} catch (ParseException e) {
e.printStackTrace();
}
return s2;
}
Similarly i have other two methods which will return data in yyyyMM and dd formats ??
This works fine , but does not look good
My question is can we have only one utility which satisfies my requirement ??
My question is can we have only one utility which satisfies my requirement ??
I think you're going about this the wrong way to start with. Fundamentally the data is just a date. You can apply formats later, when you need to. I suggest you start using Joda Time and make your method return a LocalDate. That captures all the real information, and you can then have three separate DateTimeFormatter objects used to format the value whenever you want.
Wherever you can, represent data using a type which most naturally represents the real information. Get your data into that natural format as early as possible, and keep it in that format until you have to convert it into something else (such as a string).
You could define a single method and receive as a parameter the string with the expected date format, the three strings with the formats could be defined as constants.
Yes, you could group the three methods together, and use an additional argument (an enum, for example) to specify which kind of output format you want. But I would not do that. Your solution is cleaner. Why do you think it doesn't look good?
What I would do, however, is transforming the String to a Date once and for all, and using a Date everywhere rather than the String, and transforming the Date with one of your 3 methods (which would take a Date as argument rather than a String) when needed.
The Apache Commons Lang library already has utility methods to do this for you.
For example:
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
///
// first, convert the string to a date object
Date parsedDate = DateUtils.parseDate("2012-05-25T16:10:30.000",
new String[] {"yyyy-MM-dd'T'HH:mm:ss.SSS"});
// now, format the date object to a string, using different formats
String formattedDate = DateFormatUtils.format(parsedDate, "MM/yyyy");
String formattedDate2 = DateFormatUtils.format(parsedDate, "yyyyMM");
Take a look at DateFormatUtils and DateUtils for more information.
You could just have a Date class which has the three methods. Like below:
public class MyDate {
private String date = null;
public MyDate(String date) {
this.date = date;
}
public String getMonthYear() {
return null;
}
public String getYearMonth() {
return null;
}
public String getDay() {
return null;
}
}
You can format the String into three different Strings in the constructor and just return those strings on method calls. That implementation would be good if you make numberous/repeated calls on the same date string. Or you could format the string in the method call, if you are doing it once but if you are doing it once you may want to make the class/methods static and get rid of the constructor.