Code is Poetry

Brian Bilston has written a History of Modern Art in Poetry.  I  wondered what it would be like to do something similar in various programming languages.

Here’s the original poem:

Roses are red
Violets are blue
Sugar is sweet
And so are you

Haskell

Here’s the poem constructed using a zip statement in Haskell

Prelude> zip ["roses","violets","sugar","you"]["red","blue","sweet","sweet"]
[("roses","red"),("violets","blue"),("sugar","sweet"),("you","sweet")]

The list produced holds the relationship that sugar is sweet and you are sweet. The comparison between “you” and sugar is not made clear.

Lisp

Here’s the poem stored as an alist in Lisp

(setq poem '(("roses" . "red") ("violets" . "blue") ("sugar" . "sweet")("you" . "sweet")))
(mapcar (lambda (x) (concat (car x) " are " (cdr x))) poem)

I’ve gone one stage further here, using a mapcar function to produce something that looks a little bit more like the original poem, however we’re still missing the connection between “you” and sugar.

("roses are red" "violets are blue" "sugar are sweet" "you are sweet")

Python

Of course, sugar are sweet isn’t right.   Let’s try some Python.

poem = {"roses":"red","violets":"blue","sugar":"sweet","you":"sweet"}

for key, value in poem.items():
    if key == "sugar":
        print(key, "is" ,value)
    else:
        print(key, "are", value)

This output is at least grammatically correct.

roses are red
violets are blue
sugar is sweet
you are sweet

Java

Java can do something similar using a HashMap

Map<String, String> poem = new HashMap<String, String>();

        poem.put("roses", "red");
        poem.put("violets", "blue");
        poem.put("sugar", "sweet");
        poem.put("you", "sweet");

        for (Map.Entry<String, String> entry : poem.entrySet()) {
            if(entry.getKey().equals("sugar")){
                System.out.println(entry.getKey() + " is " + entry.getValue());
            } else{
                System.out.println(entry.getKey() + " are " + entry.getValue());
            }
            
        }

But we’re still no closer to conveying the connection between “you” being sweet, just like sugar is sweet.

Fortunately, Java allows us to use some object oriented design to better convey the meaning of the poem.

In the example below I’ve used an interface to allow sweetness to be applied to both sugar and to the special one to whom the poem refers.  The comparison is at last made clear.  As there can only be one true love, it seemed reasonable to make a singleton class for TheOne, inherited from a regular person.

Run the code and the poem is printed out properly, just like the original.  More importantly though, the concepts to which the poem refers are properly encapsulated and related.

The original poem was only 4 lines long.  My implementation takes 80 lines, but I think you’ll agree I’ve done a rather better job, providing clarity and removing any ambiguity.

public class Love {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Flower [] rose = new Flower[12]; // 12 roses in a bunch
        Flower [] violet = new Flower[30]; // more violets in bunch
        Sugar sugar = new Sugar();
        TheOne myLove = TheOne.getInstance();  // Singleton class
        // There can only be one true love
        
        rose[0] = new Flower();
        rose[0].setColour("red");  // colour is static so only need
                                    // to instantiate one here
        
        violet[0] = new Flower();
        violet[0].setColour("blue");
        
        System.out.println("Roses are " + rose[0].getColour());
        System.out.println("Violets are " + violet[0].getColour());
        System.out.println(sugar.sweet());
        System.out.println(myLove.sweet());
    }
    
}

class Flower {
    private static String colour;
    
    public void setColour(String colour){
        this.colour = colour;
    }
    
    public String getColour (){
        return colour;
    }
}

class Sugar implements Sweetness {

    @Override
    public String sweet() {
        return "Sugar is sweet";
    }
    
}

class Person {
    public String sweet()
    {
        return "Not sweet";
    }
}

class TheOne extends Person implements Sweetness{
    private static TheOne instance = null;
    
    private TheOne()
    {
        
    }
    
    public static TheOne getInstance()
    {
        if(instance == null)
            instance = new TheOne();
        
        return instance;
    }

    @Override
    public String sweet() {
         return "And so are you";
    }
}

interface Sweetness {
    String sweet();
}

JDBC 8: The Complete Code

package dbase2016;

/**
 *
 * @author ajb
 */
public class DBase2016 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
    GUIAddStudent  addStudent = new GUIAddStudent();
    addStudent.setVisible(true);
    }

}
package dbase2016;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

/**
 *
 * @author ajb
 */
public class DBase {

    private static Connection con;

    DBase() {
    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
    } catch (Exception ex) {
        System.err.println(ex);
    }

    }

    public static void makeConnection() {
    try {
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bluecoat", "root", "");
    } catch (SQLException ex) {
        System.err.println(ex);
    }

    }

    public static void printPupils() {

    Statement statement;
    makeConnection();
    try {
        statement = con.createStatement();
        ResultSet rs = statement.executeQuery("SELECT * FROM Student");

        while (rs.next()) {
        System.out.println("Forename: " + rs.getString("Forename") 
                  + " Surname: " + rs.getString("Surname")
                  + " Gender: " + rs.getString("Gender") 
                  + " Form: " + rs.getString("Form"));
        }

        con.close();

    } catch (SQLException ex) {
        System.err.println(ex);
    }
    }

    public static ArrayList<Student> getPupils()
    {
    ArrayList<Student> students = new ArrayList();
    Statement statement;
    makeConnection();
    try {
        statement = con.createStatement();
        ResultSet rs = statement.executeQuery("SELECT * FROM Student");

        while (rs.next()) {

        Student student = new Student();
        student.setForename(rs.getString("Forename")); 
        student.setSurname(rs.getString("Surname"));
        student.setGender(rs.getString("Gender"));
        student.setForm(rs.getString("Form"));
        students.add(student);
        }

        con.close();

    } catch (SQLException ex) {
        System.err.println(ex);
    }

    return students;
    }

    public static void addStudent() {

    makeConnection();
    try {
        PreparedStatement prep = con.prepareStatement("INSERT INTO Student (Forename, Surname, Gender, Form) VALUES (?,?,?,?)");
        prep.setString(1, "Last");
        prep.setString(2, "James");
        prep.setString(3, "M");
        prep.setString(4, "9C");

        prep.executeUpdate();

        con.close();

    } catch (SQLException ex) {
        System.err.println(ex);
    }

    }

    public static void addStudent(Student student) {

    makeConnection();
    try {
        PreparedStatement prep = con.prepareStatement("INSERT INTO Student (Forename, Surname, Gender, Form) VALUES (?,?,?,?)");
        prep.setString(1, student.getForename());
        prep.setString(2, student.getSurname());
        prep.setString(3, student.getGender());
        prep.setString(4, student.getForm());

        prep.executeUpdate();

        con.close();

    } catch (SQLException ex) {
        System.err.println(ex);
    }

    }

}
package dbase2016;

/**
 *
 * @author ajb
 */
public class Student {
    private String forename;
    private String surname;
    private String gender;
    private String form;

    /**
     * @return the forename
     */
    public String getForename() {
    return forename;
    }

    /**
     * @param forename the forename to set
     */
    public void setForename(String forename) {
    this.forename = forename;
    }

    /**
     * @return the surname
     */
    public String getSurname() {
    return surname;
    }

    /**
     * @param surname the surname to set
     */
    public void setSurname(String surname) {
    this.surname = surname;
    }

    /**
     * @return the gender
     */
    public String getGender() {
    return gender;
    }

    /**
     * @param gender the gender to set
     */
    public void setGender(String gender) {
    this.gender = gender;
    }

    /**
     * @return the form
     */
    public String getForm() {
    return form;
    }

    /**
     * @param form the form to set
     */
    public void setForm(String form) {
    this.form = form;
    }

}
package dbase2016;

import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

/**
 *
 * @author ajb
 */
public class GUIDisplayStudents extends JFrame {

    JTextArea textArea;
    JScrollPane scrollPane;

    GUIDisplayStudents()
    {
    this.setSize(300,200);
    this.setLocationRelativeTo(null);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    textArea = new JTextArea("Sample Text");
    scrollPane = new JScrollPane(textArea);
    add(scrollPane);

    }

    GUIDisplayStudents(ArrayList<Student> students)
    {
    this.setSize(300,200);
    this.setLocationRelativeTo(null);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    textArea = new JTextArea();
    scrollPane = new JScrollPane(textArea);
    for(Student student : students)
    {            
        textArea.append(student.getForename() + " " + student.getSurname() + "\n");
    }
    add(scrollPane);

    }

}
package dbase2016;

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

/**
 *
 * @author ajb
 */
public class GUIAddStudent extends JFrame implements ActionListener{
    
    JLabel lblForename = new JLabel("Forename");
    JLabel lblSurname = new JLabel("Surname");
    JLabel lblGender = new JLabel("Gender");
    JLabel lblForm = new JLabel("Form");
    
    JTextField txtForename = new JTextField("");
    JTextField txtSurname = new JTextField("");
    JTextField txtGender = new JTextField("");
    JTextField txtForm = new JTextField("");
    
    JButton OK = new JButton("OK");
   
    
    GUIAddStudent()
    {
        Container vert = Box.createVerticalBox();
        vert.add(lblForename);
        vert.add(txtForename);
        vert.add(lblSurname);
        vert.add(txtSurname);
        vert.add(lblGender);
        vert.add(txtGender);
        vert.add(lblForm);
        vert.add(txtForm);
        
        vert.add(OK);
        
        OK.addActionListener(this);
        add(vert);
        
        this.setSize(300,250);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        
    }

    @Override
    public void actionPerformed(ActionEvent ae) {
        Student student = new Student();
        student.setForename(txtForename.getText());
        student.setSurname(txtSurname.getText());
        student.setGender(txtGender.getText());
        student.setForm(txtForm.getText());
        
        DBase.addStudent(student);
        
        GUIDisplayStudents  displayPupils = new GUIDisplayStudents(DBase.getPupils());
        displayPupils.setVisible(true);
    }
    
}

JDBC 7: Adding Students using a GUI

Create DBase.addStudent(Student student) Method

public static void addStudent(Student student) {
makeConnection();
try {
PreparedStatement prep = con.prepareStatement("INSERT INTO Student (Forename, Surname, Gender, Form) VALUES (?,?,?,?)");
prep.setString(1, student.getForename());
prep.setString(2, student.getSurname());
prep.setString(3, student.getGender());
prep.setString(4, student.getForm());
prep.executeUpdate();
con.close();
} catch (SQLException ex) {
System.err.println(ex);
}
}

Create GUIAddStudent Class

The following code will display the simple GUI shown

package dbase2016;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
/**
*
* @author ajb
*/
public class GUIAddStudent extends JFrame implements ActionListener{
JLabel lblForename = new JLabel("Forename");
JLabel lblSurname = new JLabel("Surname");
JLabel lblGender = new JLabel("Gender");
JLabel lblForm = new JLabel("Form");
JTextField txtForename = new JTextField("");
JTextField txtSurname = new JTextField("");
JTextField txtGender = new JTextField("");
JTextField txtForm = new JTextField("");
JButton OK = new JButton("OK");
GUIAddStudent()
{
Container vert = Box.createVerticalBox();
vert.add(lblForename);
vert.add(txtForename);
vert.add(lblSurname);
vert.add(txtSurname);
vert.add(lblGender);
vert.add(txtGender);
vert.add(lblForm);
vert.add(txtForm);
vert.add(OK);
OK.addActionListener(this);
add(vert);
this.setSize(300,250);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent ae) {
Student student = new Student();
student.setForename(txtForename.getText());
student.setSurname(txtSurname.getText());
student.setGender(txtGender.getText());
student.setForm(txtForm.getText());
DBase.addStudent(student);
GUIDisplayStudents displayPupils = new GUIDisplayStudents(DBase.getPupils());
displayPupils.setVisible(true);
}
}

JDBC 6: Get Pupils and Display in GUI

Create a DBase.getPupils() method

A method to fetch all the pupils. They are wrapped in the Student class and then returned as an ArrayList

public static ArrayList<Student> getPupils()
    {
    ArrayList<Student> students = new ArrayList();
    Statement statement;
    makeConnection();
    try {
        statement = con.createStatement();
        ResultSet rs = statement.executeQuery("SELECT * FROM Student");

        while (rs.next()) {

        Student student = new Student();
        student.setForename(rs.getString("Forename")); 
        student.setSurname(rs.getString("Surname"));
        student.setGender(rs.getString("Gender"));
        student.setForm(rs.getString("Form"));
        students.add(student);
        }

        con.close();

    } catch (SQLException ex) {
        System.err.println(ex);
    }

    return students;
    }

Use the getPupils() method in the GUI

package dbase2016;

import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

/**
 *
 * @author ajb
 */
public class GUIDisplayStudents extends JFrame {

    JTextArea textArea;
    JScrollPane scrollPane;

    GUIDisplayStudents(ArrayList<Student> students)
    {
    this.setSize(300,200);
    this.setLocationRelativeTo(null);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    textArea = new JTextArea();
    scrollPane = new JScrollPane(textArea);
    for(Student student : students)
    {            
        textArea.append(student.getForename() + " " + student.getSurname() + "\n");
    }
    add(scrollPane);

    }

}
package dbase2016;

/**
 *
 * @author ajb
 */
public class DBase2016 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
    GUIDisplayStudents  displayPupils = new GUIDisplayStudents(DBase.getPupils());
    displayPupils.setVisible(true);
    }

}

JDBC 5: Creating a GUI

A simple GUI to display database contents

package dbase2016;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

/**
 *
 * @author ajb
 */
public class GUIDisplayStudents extends JFrame {

    JTextArea textArea;
    JScrollPane scrollPane;

    GUIDisplayStudents()
    {
    this.setSize(300,200);
    this.setLocationRelativeTo(null);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    textArea = new JTextArea("Sample Text");
    scrollPane = new JScrollPane(textArea);
    add(scrollPane);

    }

}

Student Class

This will be used to wrap the data retrieved from the database

package dbase2016;

/**
 *
 * @author ajb
 */
public class Student {
    private String forename;
    private String surname;
    private String gender;
    private String form;

    /**
     * @return the forename
     */
    public String getForename() {
    return forename;
    }

    /**
     * @param forename the forename to set
     */
    public void setForename(String forename) {
    this.forename = forename;
    }

    /**
     * @return the surname
     */
    public String getSurname() {
    return surname;
    }

    /**
     * @param surname the surname to set
     */
    public void setSurname(String surname) {
    this.surname = surname;
    }

    /**
     * @return the gender
     */
    public String getGender() {
    return gender;
    }

    /**
     * @param gender the gender to set
     */
    public void setGender(String gender) {
    this.gender = gender;
    }

    /**
     * @return the form
     */
    public String getForm() {
    return form;
    }

    /**
     * @param form the form to set
     */
    public void setForm(String form) {
    this.form = form;
    }

}

JDBC 4: The Code so Far…

The Code so Far

package dbase2016;

/**
 *
 * @author ajb
 */
public class DBase2016 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
    DBase.addStudent();
    DBase.printPupils();
    }

}
package dbase2016;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author ajb
 */
public class DBase {

    private static Connection con;

    DBase() {
    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
    } catch (Exception ex) {
        System.err.println(ex);
    }

    }

    public static void makeConnection() {
    try {
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bluecoat", "root", "");
    } catch (SQLException ex) {
        System.err.println(ex);
    }

    }

    public static void printPupils() {

    Statement statement;
    makeConnection();
    try {
        statement = con.createStatement();
        ResultSet rs = statement.executeQuery("SELECT * FROM Student");

        while (rs.next()) {
        System.out.println("Forename: " + rs.getString("Forename") 
                  + " Surname: " + rs.getString("Surname")
                  + " Gender: " + rs.getString("Gender") 
                  + " Form: " + rs.getString("Form"));
        }

        con.close();

    } catch (SQLException ex) {
        System.err.println(ex);
    }
    }

    public static void addStudent() {

    makeConnection();
    try {
        PreparedStatement prep = con.prepareStatement("INSERT INTO Student (Forename, Surname, Gender, Form) VALUES (?,?,?,?)");
        prep.setString(1, "Last");
        prep.setString(2, "James");
        prep.setString(3, "M");
        prep.setString(4, "9C");

        prep.executeUpdate();

        con.close();

    } catch (SQLException ex) {
        System.err.println(ex);
    }

    }

}

JDBC 3: Queries

Fetch ResultSet

Once you have a connection, you can now fetch data from the database. Add the following method to the DBase class.

  • The method creates a statement attached to the connection con.
  • The statement executes a simple MySQL query. The query results are stored in a ResultSet rs.
  • A pointer is set to before the first record in the ResultSet.
  • A while statement is used to traverse the set.
  • Finally, the connection is closed.
public static void printPupils() {

    Statement statement;
    makeConnection();
    try {
        statement = con.createStatement();
        ResultSet rs = statement.executeQuery("SELECT * FROM Student");

        while (rs.next()) {
        System.out.println("Forename: " + rs.getString("Forename") 
                  + " Surname: " + rs.getString("Surname")
                  + " Gender: " + rs.getString("Gender") 
                  + " Form: " + rs.getString("Form"));
        }

        con.close();

    } catch (SQLException ex) {
        System.err.println(ex);
    }
}
package dbase2016;

/**
 *
 * @author ajb
 */
public class DBase2016 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

    DBase.printPupils();
    }

}

Add a record using a PreparedStatement

Note that we use executeQuery() to retrieve data and executeUpdate() to update the database.  Here we’ve hard coded the student we’re adding.   A later section will show how to add any student.

public static void addStudent() {

       makeConnection();
       try {
       PreparedStatement prep 
           = con.prepareStatement("INSERT INTO Student
        (Forename, Surname, Gender, Form) 
           VALUES (?,?,?,?)");
       prep.setString(1, "Last");
       prep.setString(2, "James");
       prep.setString(3, "M");
       prep.setString(4, "9C");

       prep.executeUpdate();

       con.close();

       } catch (SQLException ex) {
       System.err.println(ex);
       }

   }
package dbase2016;

/**
 *
 * @author ajb
 */
public class DBase2016 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
    DBase.addStudent();
    DBase.printPupils();
    }

}

JDBC 2: Database Class

The following is the class I’m going to use for the main part of this tutorial. It’s just the Quick Start code broken down into methods.

package dbase2016;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author ajb
 */
public class DBase {

    private static Connection con;

    DBase() {
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
        } catch (Exception ex) {
            System.err.println(ex);
        }

    }

    public static void makeConnection() {
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bluecoat", "root", "");
        } catch (SQLException ex) {
            System.err.println(ex);
        }

    }


    }

}

Check the connection by calling the makeConnection() method as follows. If everything is okay the program will simply terminate. If an exception is thrown, check your port number, username and password.

package dbase2016;

/**
 *
 * @author ajb
 */
public class DBase2016 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
    DBase.makeConnection();
    }

}

– More Collections: Return to Lisp Problems Solutions

1 Last Item

Find the last item in an List of String objects

1.1 Solution

1: String lastItem(List<String> a)
2: {
3:     return  a.get(a.size()-1);
4: }

2 Last Item Generic

Find the last item in a Generic List

2.1 Solution

1: Object gLastItem(List<?> a)
2: {
3:     return  a.get(a.size()-1);
4: }

3 Last But One

Find the last but one item in a List

3.1 Solution

1: Object lastButOneItem(List<?> a)
2: {
3:     if (a.size() > 1) 
4:  return  a.get(a.size()-2);
5:     else  
6:  return "List too small";
7: }

4 Iterate through the Elements of a List

Iterate through the Elements of a List, printing them out in turn

4.1 Solution

1: void printEach(List<?> a)
2: {
3:     for (Object e: a)
4:     {
5:  System.out.println(e);
6:     }        
7: }

or using a stream

1: void streamPrintEach(List<?> list)
2: {
3:     list
4:  .stream()
5:  .forEach(System.out::println);
6: 
7: }

5 Eliminate consecutive duplicates from a List.

Write a method that removes consecutive duplicates from a List. The order of the elements should not be changed.

5.1 Solution

1: List<?> removeDuplicates(List<?> a)
2: {
3:     for (int i = 0; i<a.size()-1; i++)
4:     {
5:  if(a.get(i) == a.get(i+1)) a.remove(a.get(i));        
6:     }
7:     return a;
8: }

6 Eliminate consecutive duplicates from a List using HashSet

Remembering that a HashSet cannot contain duplicates, repeat the above question using a HashSet

6.1 Solution

1: HashSet<String> hashRemoveDuplicates(List<String> a)
2: {
3:     HashSet<String> hSet = new HashSet<String>(a);
4:     return hSet;
5: }

7 RLE

Run-length encoding of a list. Consecutive duplicates of elements are encoded as pairs where N is the number of duplicates of the element E.

Note this solution uses the Pair class, defined in the question

7.1 Solution

 1: List<Pair> RLE(List<?> list)
 2: {
 3:     List<Pair> encoded = new ArrayList<Pair>();
 4:     for (int i = 0; i < list.size(); i++)
 5:     {
 6:     int runLength = 1;
 7:     while (i < list.size() -1 && list.get(i) == list.get(i+1))
 8:     {
 9:         runLength++;
10:         i++;
11:     }
12: 
13:      Pair<Object> pair = new Pair<Object>(runLength, list.get(i));
14:      encoded.add(pair);
15:     }
16:     return encoded;
17: 
18: }

8 Decode a run-length encoded list

Given a run-length code list generated in a previous problem, construct its uncompressed version.

Note this solution uses the Pair class, defined in the question

8.1 Solution

 1: List<Object> decodeRLE(List<Pair> list)
 2: {
 3: 
 4:     List<Object> decoded = new ArrayList<Object>();
 5:     for (Pair pair: list)
 6:     {
 7:     for (int i =0; i<(int)pair.count; i++)
 8:     {
 9:         decoded.add(pair.value);
10:     }
11:     }
12: 
13:     return decoded;
14: }

9 Duplicate the elements of a list

9.1 Solution

 1: List<String> dupli(List<String> list)
 2: {
 3:     List<String> dup = new ArrayList<String>();
 4: 
 5:     for(String s: list)
 6:     {
 7:     dup.add(s);
 8:     dup.add(s);
 9:     }
10: 
11:     return dup;
12: }

or, using a stream

1: List<String> streamDupli(List<String> list)
2: {
3:     List<String> dupli = list
4:              .stream()
5:              .collect(Collectors.toList());
6: 
7:     return dupli;        
8: 
9: }

10 Replicate the elements of a list a given number of times

10.1 Solution

 1: List<String> repli(List<String> list, int num)
 2: {
 3:     List<String> rep = new ArrayList<String>();
 4: 
 5:     for(String s: list)
 6:     {
 7:     for (int i=0; i<num; i++)
 8:     {
 9:         rep.add(s);
10:     }
11:     }
12: 
13:     return rep;
14: }

7: More Collections: Return to Lisp Problems

These problems were inspired by the 99 Lisp problems. Lisp is a very different language to Java; its use of lists means it’s not appropriate to emulate all the original problems in Java, however, there is some benefit in practising the use of Java collections.

The introduction of lambda functions in Java8 made me rethink how best to approach these problems. There are three things being practised here: collections, generics and lambdas. I’ve split up the questions so that they give a chance to practice these different skills.

1 Last Item

Find the last item in an List of String objects

1.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "fork", "spoon"));
2: System.out.println(lastItem(myList));
3:  *** Output ***
4: spoon

2 Last Item Generic

Find the last item in a Generic List

2.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "fork", "spoon"));
2: List<Integer> anotherList = new ArrayList<>(asList(1,2,3));
3: System.out.println(gLastItem(myList));
4: System.out.println(gLastItem(anotherList));
5:  *** Output ***
6: spoon
7: 3

3 Last But One

Find the last but one item in a List

3.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "fork", "spoon"));
2: System.out.println(lastButOneItem(myList));
3:  *** Output ***
4: fork

4 Iterate through the Elements of a List

Iterate through the Elements of a List, printing them out in turn

4.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "fork", "spoon"));
2: System.out.println(printEach(myList));
3:  *** Output ***
4: knife
5: fork
6: spoon

5 Eliminate consecutive duplicates from a List

Write a method that removes consecutive duplicates from a List. The order of the elements should not be changed.

5.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "knife", "fork", "spoon","spoon"));
2: printEach(removeDuplicates(myList));
3:  *** Output ***
4: knife
5: fork
6: spoon

6 Eliminate consecutive duplicates from a List using HashSet

Remembering that a HashSet cannot contain duplicates, repeat the above question using a HashSet

6.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "knife", "fork", "spoon","spoon"));
2: printEach(removeDuplicates(myList));
3:  *** Output ***
4: knife
5: fork
6: spoon

Remembering that a HashSet cannot contain duplicates

7 RLE

Run-length encoding of a list. Consecutive duplicates of elements are encoded as pairs where N is the number of duplicates of the element E.

Use this Pair class

 1: class Pair<T>
 2:    {
 3:        int count;
 4:        T value;
 5: 
 6:        Pair(int count, T value) 
 7:        {
 8:        this.count = count;
 9:        this.value = value;
10:        }
11: 
12:        void print()
13:        {
14:        System.out.print("("+ count + ", " + value +") ");
15:        }
16:    } 

7.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "knife", "fork", "spoon","spoon"));
2:  List<Pair> rle = RLE(myList);
3:  for (Pair r: rle)
4:  {
5:      r.print();
6:  }
7:  System.out.println("");
8:  *** Output ***
9: (2, knife) (1, fork) (2, spoon)

8 Decode a run-length encoded list

Given a run-length code list generated in a previous problem, construct its uncompressed version.

8.1 Example

 1: List<String> myList = new ArrayList<>(asList("knife", "knife", "fork", "spoon","spoon"));
 2:     List<Pair> rle = RLE(myList);
 3:     for (Pair r: rle)
 4:     {
 5:         r.print();
 6:     }
 7:     System.out.println("");
 8: 
 9:     List<Object> decoded = decodeRLE(rle);
10: 
11:     for (Object o: decoded)
12:     {
13:         System.out.println(o);
14:     }
15:  *** Output ***
16: (2, knife) (1, fork) (2, spoon) 
17: knife
18: knife
19: fork
20: spoon
21: spoon

9 Duplicate the elements of a list

9.1 Example

 1: List<String> myList = new ArrayList<>(asList("knife", "knife", "fork", "spoon","spoon"));
 2: printEach(dupli(myList));
 3:  *** Output ***
 4: knife
 5: knife
 6: knife
 7: knife
 8: fork
 9: fork
10: spoon
11: spoon
12: spoon
13: spoon

10 Replicate the elements of a list a given number of times

10.1 Example

 1: List<String> myList = new ArrayList<>(asList("knife", "knife", "fork", "spoon","spoon"));
 2: printEach(repli(myList,3));
 3:  *** Output ***
 4: knife
 5: knife
 6: knife
 7: knife
 8: knife
 9: knife
10: fork
11: fork
12: fork
13: spoon
14: spoon
15: spoon
16: spoon
17: spoon
18: spoon