How to solve programming tasks with GPT powered chatbot

Photo by D koi on Unsplash

Code generation to the rescue

As you probably have heard by this time ChatGPT a machine learning based chatbot created by OpenAI is very famous. It is based on Generative Pretrained Transformer model, hence, GPT in short. It’s quite successful in various tasks ranging from text summarization, essays generation to questions answering. But did you know that it can also generate working code in various programming languages? If you didn’t then this post will provide you with some ideas to try.

Task at hand

For example, in the JSON Crack online tool below you can see how such a list of objects can look like

To summarize what needs to be done is as follows

Using Java Stream API approach

Java 8 version introduced a powerful Streams API that allows processing of collections in a functional way. For example, it is possible to filter, apply mapping or sorting to a collection in a single line of code using a declarative syntax somewhat similar to SQL. So, accomplishing the task of sorting a list of objects that have a createdDate field of Date type is quite simple and if you google how to do it you’ll find a number of solutions.

For example, this is how it can be done based on the Stack Overflow answer.

List<Order> orders = list.stream().
                        sorted(comparing(Order::getCreatedDate).
                        collect(Collectors.toList());

First prompt

Write a java code to sort a list of objects while converting a string field to date type

and this is the solution that the Bing chatbot provided


Certainly! Here’s an example of a Java code snippet that sorts a list of objects while converting a string field to date type:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<YourObject> yourList = new ArrayList<>();
        // Add objects to yourList

        // Sort the list based on the string field "dateString"
        Collections.sort(yourList, new Comparator<YourObject>() {
            @Override
            public int compare(YourObject o1, YourObject o2) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    Date date1 = dateFormat.parse(o1.getDateString());
                    Date date2 = dateFormat.parse(o2.getDateString());
                    return date1.compareTo(date2);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                return 0;
            }
        });

        // Print the sorted list
        for (YourObject obj : yourList) {
            System.out.println(obj);
        }
    }
}

class YourObject {
    private String dateString;

    public String getDateString() {
        return dateString;
    }

    public void setDateString(String dateString) {
        this.dateString = dateString;
    }

    // Add other fields and methods as needed
}

In this example, we have a list of objects of type YourObject that contains a string field called dateString. We want to sort the list based on this field, treating it as a date.

To achieve this, we use the Collections.sort() method and provide a custom Comparator implementation. Inside the compare() method, we parse the dateString of each object into a Date object using a SimpleDateFormat. We then compare the two dates using the compareTo() method and return the result.

Please note that you need to replace YourObject with the actual class name and modify the code according to your specific requirements.

Let me know if you need any further assistance!

Second more nuanced prompt

write code to sort a list of objects while converting a string field to date type using java stream api

Certainly! Here’s an example of a Java code snippet that sorts a list of objects while converting a string field to date type using the Java Stream API:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<YourObject> yourList = new ArrayList<>();
        // Add objects to yourList

        // Sort the list based on the string field "dateString" using Java Stream API
        yourList.sort(Comparator.comparing(obj -> {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date date = dateFormat.parse(obj.getDateString());
                return date;
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return null;
        }));

        // Print the sorted list
        yourList.forEach(System.out::println);
    }
}

class YourObject {
    private String dateString;

    public String getDateString() {
        return dateString;
    }

    public void setDateString(String dateString) {
        this.dateString = dateString;
    }

    // Add other fields and methods as needed
}

In this example, we have a list of objects of type YourObject that contains a string field called dateString. We want to sort the list based on this field, treating it as a date.

To achieve this using the Java Stream API, we use the sort() method of the List interface and provide a lambda expression as the comparator. Inside the lambda expression, we parse the dateString of each object into a Date object using a SimpleDateFormat. We then return the parsed date for comparison.

Please note that you need to replace YourObject with the actual class name and modify the code according to your specific requirements.

Let me know if you need any further assistance!

Testing the generated code almost as is in an online Java compiler

Well, that last answer was what I needed. We can take it and check that it can run almost as is in an online Java compiler. I made a couple of small adjustments in the generated code:

  • I instantiated three objects with dateString populated.
  • I added these objects to a list and
  • I adjusted println function to print the dateString field, instead of the object itself.

This is how it looked after running

// Online Java Compiler
// Use this editor to write, compile and run your Java code online

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<YourObject> yourList = new ArrayList<>();
        // Add objects to yourList
        YourObject obj1 = new YourObject();
        obj1.setDateString("2023-09-01");
        
        YourObject obj2 = new YourObject();
        obj2.setDateString("2022-07-02");
        
        YourObject obj3 = new YourObject();
        obj3.setDateString("2021-08-06");
        
        yourList.add(obj1);
        yourList.add(obj2);
        yourList.add(obj3);

        // Sort the list based on the string field "dateString" using Java Stream API
        yourList.sort(Comparator.comparing(obj -> {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date date = dateFormat.parse(obj.getDateString());
                return date;
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return null;
        }));

        // Print the sorted list
        yourList.forEach((obj -> System.out.println(obj.getDateString())));
    }
}

class YourObject {
    private String dateString;

    public String getDateString() {
        return dateString;
    }

    public void setDateString(String dateString) {
        this.dateString = dateString;
    }
    

    // Add other fields and methods as needed
}

Blowing your socks off

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.