HW4

HW4 – DateTime Parse

private static final SimpleDateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

// use comma as separator
String[] items = line.split(delimiter);
Date dateTime = null;
try {
      dateTime = formatter.parse(items[0]);
}
catch (ParseException e) {
      e.printStackTrace();
}

/////////////////////////DateParseTest.java////////////////////////////////////////

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.io.FileNotFoundException;
import java.util.*;

public class DateParseTest {
 private static final SimpleDateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

 public static void main(String[] args)  {
  String date=”1980-12-29 13:00:06″;

  Date dateTime = null;
  try {
   dateTime = formatter.parse(date);
  }
  catch (ParseException e) {
   e.printStackTrace();
  }
  System.out.println(formatter.format(dateTime));
 }
}

Point Collections

1. create PointLib package
– Point 클래스를 넣는다.
package PointLib;

import java.util.*;

public class Point implements Comparable<Point> {
protected double x;
protected double y;

public Point()
{
this(0.0, 0.0);
}

public Point(double x, double y)
{
this.x = x;
this.y = y;
}

public double getX()
{
return x;
}

public double getY()
{
return y;
}

public int compareTo(Point other)
{
return Double.compare(this.getX(), other.getX()); //ascending order by X
}

public static Comparator<Point> YComparator = new Comparator<Point>() {
public int compare(Point p1, Point p2) {
return Double.compare(p1.getY(), p2.getY()); //ascending order by Y
}
};

@Override
public int hashCode() // hashCode method override
{
return Double.valueOf(this.x).hashCode() * Double.valueOf(this.y).hashCode();
}

@Override
public boolean equals(Object obj) // equals method override
{
if (obj instanceof Point)
return equals((Point)obj);
return false;
}

public boolean equals(Point other) // equals method override
{
if (this.x == other.x && this.y == other.y)
return true;
return false;
}

@Override
public String toString() // toString method override
{
return “(” + this.x + “,” + this.y + “)”;
}

}

 

2. create PointCollectionLab package
– PointTest 클래스를 넣는다.
package PointTestApp;

import java.util.*;
import java.util.function.*;
import java.util.stream.Collectors;

import PointLib.Point;

class PointTest  {

public static void main(String[] args) {
new PointTest();
}

public PointTest()
{
Point[] pList = new Point[10];
for (int i=0; i<10; i++) {
pList[i] = new Point(i, i+1);
}
System.out.println(“Point!!!”);
Arrays.stream(pList).forEach((s) -> System.out.println(s));

System.out.println(“Point SORT BY X (DEFAULT)!!!”);
Arrays.sort(pList);
Arrays.stream(pList).forEach((s) -> System.out.println(s));

System.out.println(“Person SORT by Y!!!”);
Arrays.sort(pList, Point.YComparator);
Arrays.stream(pList).forEach((s) -> System.out.println(s));

///////////////////////////////////////////////////////////////////////
System.out.println(“Point SORT BY X (anonymous method)!!!”);
Arrays.sort(pList, new Comparator<Point>() {
public int compare(Point p1, Point p2) {
return Double.compare(p1.getX(), p2.getX()); //ascending order by X
}
});
Arrays.stream(pList).forEach((s) -> System.out.println(s));

System.out.println(“Point SORT by Y (anonymous method)!!!”);
Arrays.sort(pList, new Comparator<Point>() {
public int compare(Point p1, Point p2) {
return Double.compare(p1.getY(), p2.getY()); //ascending order by Y
}
});
Arrays.stream(pList).forEach((s) -> System.out.println(s));

///////////////////////////////////////////////////////////////////////
System.out.println(“Point SORT BY X (lambda)!!!”);
Arrays.sort(pList, (Point p1, Point p2)
-> Double.compare(p1.getX(), p2.getX())  );
Arrays.stream(pList).forEach((s) -> System.out.println(s));

System.out.println(“Point SORT by Y (lambda)!!!”);
Arrays.sort(pList, (Point p1, Point p2)
-> Double.compare(p1.getY(), p2.getY()) );
Arrays.stream(pList).forEach((s) -> System.out.println(s));

///////////////////////////////////////////////////////////////////////
ArrayList pointList = new ArrayList();
for (int i=0; i<10; i++) {
pointList.add(new Point(i*10, i*10+1));
}
pointList.forEach((s) -> System.out.println(s));
/*
System.out.println(“Point SORT BY X (lambda)!!!”);
pointList.sort((Point pp1, Point pp2)
-> Double.compare(pp1.getX(), pp2.getX())
);
pointList.forEach((s) -> System.out.println(s));

System.out.println(“Point SORT by Y (lambda)!!!”);
pointList.sort((Point p1, Point p2) ->
Double.compare(p1.getY(), p2.getY())
);
pointList.forEach((s) -> System.out.println(s));
*/
System.out.println(“pointList[2]=” + pointList.get(2));

Iterator it = pointList.iterator(); // Iterator 객체 얻기
while(it.hasNext()) {
Object p = it.next();
System.out.println(p);
}

///////////////////////////////////////////////////////////////////////

Vector vList= new Vector();
for (int i=0; i<10; i++) {
vList.add(new Point(i*100, i*100+1));
}
vList.forEach((s) -> System.out.println(s));

vList.removeElementAt(vList.size() – 1); // delete the last element in vList
for (int i=0; i<vList.size(); i++) {
Object p = vList.get(i);
System.out.println(p);
}

///////////////////////////////////////////////////////////////////////

Hashtable<Integer, Point> hList = new Hashtable<Integer, Point>();
for (int i=0; i<10; i++) {
hList.put(i, new Point(i*1000, i*1000+1));
}
hList.forEach((i, s) -> System.out.println(s));

System.out.println(“hList contains point (1000, 1001) is ” + hList.contains(new Point(1000, 1001)));
hList.put(10, new Point(10, 10));
hList.forEach((i, s) -> System.out.println(s));
hList.remove(9); // remove item by key
hList.forEach((i, s) -> System.out.println(s));

System.out.println(“Key,Value print”);
Set keys = hList.keySet();
Iterator itr = keys.iterator();
while(itr.hasNext()) {
Integer key = (Integer) itr.next();
Point value = hList.get(key);
System.out.println(“(” + key + “,” + value + “)”);
}

///////////////////////////////////////////////////////////////////////
System.out.println(“/////////////”);
}
}

Person FileIO & JTable

Person ArrayList & FileIO & JTable & CustomDialog & Menu

1. Person 클래스

import java.util.*;

enum Gender
{
FEMALE, MALE
}

public class Person implements Comparable<Person>
{
private String name;
private int age;
private double weight;
private double height;
private Gender gender;

public Person()
{
this(“”, 0, 0.0, 0.0, Gender.FEMALE);
}

public Person(String name, int age, double weight, double height, Gender gender)
{
this.name = name;
this.age = age;
this.weight = weight;
this.height = height;
this.gender = gender;
}

public Person(Person other)
{
this(other.name, other.age, other.weight, other.height, other.gender);
}

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

public int getAge()
{
return age;
}

public void setAge(int age)
{
this.age = age;
}

public double getWeight()
{
return weight;
}

public void setWeight(double weight)
{
this.weight = weight;
}

public double getHeight()
{
return height;
}

public void setHeight(double height)
{
this.height = height;
}

public Gender getGender()
{
return gender;
}

public void setGender(Gender gender)
{
this.gender = gender;
}

@Override
public String toString() // Object.toString() overriding
{
return String.format(“%s,%d,%.2f,%.2f,%s”, name, age, weight, height, gender.toString());
}

@Override
public boolean equals(Object other) // Object.equals overriding
{
if (other instanceof Person) {
Person that = (Person) other;
return that.canEqual(this)
&& this.getName().equals(that.getName())
&& this.getAge() == that.getAge()
&& this.getWeight() == that.getWeight()
&& this.getHeight() == that.getHeight()
&& this.getGender() == that.getGender();
}
return false;
}

@Override
public int hashCode()
{
return (41 * getName().hashCode() + getAge() + Double.valueOf(getWeight()).hashCode() + Double.valueOf(getHeight()).hashCode() + (int)(getGender()).hashCode());
}

public boolean canEqual(Object other)
{
return (other instanceof Person);
}

public int compareTo(Person other)
{
return this.getName().compareTo(other.getName()); //ascending order
}

public static Comparator<Person> AgeComparator
= new Comparator<Person>() {
public int compare(Person p1, Person p2) {
return p1.getAge() – p2.getAge(); //ascending order
}
};

public static Comparator<Person> WeightComparator
= new Comparator<Person>() {
public int compare(Person p1, Person p2) {
return Double.compare(p1.getWeight(), p2.getWeight()); //ascending order
}
};

public static Comparator<Person> HeightComparator
= new Comparator<Person>() {
public int compare(Person p1, Person p2) {
return Double.compare(p1.getHeight(), p2.getHeight()); //ascending order
}
};

public static Comparator<Person> GenderComparator
= new Comparator<Person>() {
public int compare(Person p1, Person p2) {
return p1.getGender().compareTo(p2.getGender());
}
};

}

2. PersonDialog 클래스

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

//Kyoung Shin Park (2016 Fall)
public class PersonDialog extends JDialog implements ActionListener {

public final static int OK = 1;
public final static int CANCEL = 2;
int returnValue = 0;

JLabel label1 = new JLabel(“이름”); // 레이블 초기화
JLabel label2 = new JLabel(“나이”); // 레이블 초기화
JLabel label3 = new JLabel(“몸무게”); // 레이블 초기화
JLabel label4 = new JLabel(“키”); // 레이블 초기화
JLabel label5 = new JLabel(“성별”); // 레이블 초기화

JTextField textfield1 = new JTextField(20); // 텍스트필드 초기화
JTextField textfield2 = new JTextField(20); // 텍스트필드 초기화
JTextField textfield3 = new JTextField(20); // 텍스트필드 초기화
JTextField textfield4 = new JTextField(20); // 텍스트필드 초기화

JRadioButton rbutton1 = new JRadioButton(“여자”, true); // gender 라디오버튼
JRadioButton rbutton2 = new JRadioButton(“남자”); // gender 라디오버튼
ButtonGroup rgroup = new ButtonGroup();
JPanel panel = new JPanel(); // 패널 초기화

JButton button1 = new JButton(“확인”); // 버튼 초기화

Person person = new Person();

public PersonDialog() {
setTitle(“Person Dialog”);
setLayout(null);

// frame
label1.setBounds(20, 30, 100, 20);
label2.setBounds(20, 60, 100, 20);
label3.setBounds(20, 90, 100, 20);
label4.setBounds(20, 120, 100, 20);
label5.setBounds(20, 150, 100, 20);
add(label1);
add(label2);
add(label3);
add(label4);
add(label5);

textfield1.setBounds(120, 30, 150, 20);
textfield2.setBounds(120, 60, 150, 20);
textfield3.setBounds(120, 90, 150, 20);
textfield4.setBounds(120, 120, 150, 20);

add(textfield1);
add(textfield2);
add(textfield3);
add(textfield4);
panel.add(rbutton1);
panel.add(rbutton2);
rgroup.add(rbutton1);
rgroup.add(rbutton2);
panel.setBounds(20, 150, 300, 40);
add(panel);

button1.setBounds(60, 200, 160, 20);
add(button1);

// event
button1.addActionListener(this);

setSize(300, 270); // size the frame
setResizable(false);
setModal(true);
}

private Gender selectGender()
{
if (rbutton2.isSelected()) {
return Gender.MALE;
}
return Gender.FEMALE;
}

public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if (button == button1) {
person.setName(textfield1.getText());
person.setAge(Integer.parseInt(textfield2.getText()));
person.setWeight(Double.parseDouble(textfield3.getText()));
person.setHeight(Double.parseDouble(textfield4.getText()));
person.setGender(selectGender());
returnValue = OK;
dispose();
}
}

public int getReturnValue()
{
return returnValue;
}

public Person getPerson()
{
return person;
}

/*public static void main(String[] args) {
new PersonDialog();
}*/
}

3. PersonTableModel 클래스

import java.util.*;
import javax.swing.table.*;

public class PersonTableModel extends AbstractTableModel {

private ArrayList<Person> personList;

public PersonTableModel(ArrayList<Person> pList) {
this.personList = new ArrayList<Person>(pList);
}

@Override
public int getRowCount() {
return this.personList.size();
}

@Override
public int getColumnCount() {
return 5;
}

@Override
public String getColumnName(int column) {
String name = “??”;
switch (column) {
case 0:
name = “Name”;
break;
case 1:
name = “Age”;
break;
case 2:
name = “Weight”;
break;
case 3:
name = “Height”;
break;
case 4:
name = “Gender”;
break;
}
return name;
}

@Override
public Class<?> getColumnClass(int columnIndex) {
Class<?> type = String.class;
switch (columnIndex) {
case 0:
type = String.class;
break;
case 1:
type = Integer.class;
break;
case 2:
case 3:
type = Double.class;
break;
case 4:
type = Gender.class;
break;
}
return type;
}

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Person p = this.personList.get(rowIndex);
Object value = null;
switch (columnIndex) {
case 0:
value = p.getName();
break;
case 1:
value = p.getAge();
break;
case 2:
value = p.getWeight();
break;
case 3:
value = p.getHeight();
break;
case 4:
value = p.getGender();
break;
}
return value;
}

public void setValueAt(Person value, int rowIndex) {
this.personList.set(rowIndex, value);
fireTableDataChanged();
}

public void addRow(Person p) {
this.personList.add(p);
fireTableRowsInserted(this.personList.size() – 1, this.personList.size() – 1);
}

public void removeRow(int rowIndex) {
if (rowIndex >=0 && rowIndex < getRowCount()) {
this.personList.remove(rowIndex);
fireTableRowsDeleted(rowIndex, rowIndex);
}
}
}

4. PersonTableFrame 클래스

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.table.*;
import java.io.*;

//Kyoung Shin Park (2016 Fall)
public class PersonTableFrame extends JFrame {

ArrayList<Person> personList = new ArrayList<Person>();
PersonTableModel model;

public PersonTableFrame()
{
super(“PersonTableFrame”);

model = new PersonTableModel(personList);
JTable table = new JTable(model);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setIntercellSpacing(new Dimension(10, 5));
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
int index = table.getSelectedRow();
if (index >= 0 && index < personList.size()) {
personList.remove(index);
model.removeRow(index);
//personList.forEach((s) -> System.out.println(s));
}
}
});
/*.add(new Person(“Dooly”, 1000, 40, 126.4, Gender.MALE));
personList.add(new Person(“Douner”, 1986, 30, 110, Gender.MALE));
personList.add(new Person(“Ddochi”, 30, 50, 150.5, Gender.MALE));
personList.add(new Person(“Heedong”, 3, 36, 100.6, Gender.MALE));
personList.add(new Person(“Michol”, 25, 39.8, 126.4, Gender.MALE));
personList.add(new Person(“Gildong”, 40, 38.2, 129.4, Gender.MALE));
personList.add(new Person(“Younghi”, 10, 47.2, 152.4, Gender.FEMALE));
personList.add(new Person(“Cheolsoo”, 10, 48.2, 155.4, Gender.MALE));
personList.forEach((s) -> System.out.println(s));
personList.forEach((s) -> model.addRow(s));*/

personList = loadCSV(“data/PersonList.csv”);
personList.forEach((s) -> model.addRow(s));
//personList.forEach((s) -> System.out.println(s));
//saveCSV(“TestList.csv”, personList);

JScrollPane scrollPane = new JScrollPane(table);
this.add(scrollPane, BorderLayout.CENTER);

// menu
JMenuBar menuBar = new JMenuBar();

// File Menu, F – Mnemonic
JMenu fileMenu = new JMenu(“File”);
fileMenu.setMnemonic(KeyEvent.VK_F);
menuBar.add(fileMenu);

// File->Open, O – Mnemonic
JMenuItem openMenuItem = new JMenuItem(“Open”, KeyEvent.VK_O);
fileMenu.add(openMenuItem);
this.setJMenuBar(menuBar);
openMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent event) {
System.out.println(“OPEN”);
String selectedFilename = openFileDialog();
if (selectedFilename != null) {
personList = loadCSV(selectedFilename);
personList.forEach((q) -> model.addRow(q));
}
}
});

// File->Save, O – Mnemonic
JMenuItem saveMenuItem = new JMenuItem(“Save”, KeyEvent.VK_S);
fileMenu.add(saveMenuItem);
this.setJMenuBar(menuBar);
saveMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent event) {
System.out.println(“SAVE”);
String selectedFilename = saveFileDialog();
if (selectedFilename != null) {
saveCSV(selectedFilename, personList);
}
}
});

// File->Exit, E – Mnemonic
JMenuItem exitMenuItem = new JMenuItem(“Exit”, KeyEvent.VK_E);
fileMenu.add(exitMenuItem);
this.setJMenuBar(menuBar);
exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent event) {
System.exit(0);
}
});

// Person Menu, P – Mnemonic
JMenu personMenu = new JMenu(“Person”);
personMenu.setMnemonic(KeyEvent.VK_P);
menuBar.add(personMenu);

// Person->Add, A – Mnemonic
JMenuItem addMenuItem = new JMenuItem(“Add”, KeyEvent.VK_A);
personMenu.add(addMenuItem);
this.setJMenuBar(menuBar);
addMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent event) {
PersonDialog personDialog = new PersonDialog();
personDialog.setVisible(true);
if (personDialog.getReturnValue() == PersonDialog.OK) {
Person p = personDialog.getPerson();
//System.out.println(p);
model.addRow(p);
personList.add(p);
System.out.println(“After add:”);
personList.forEach((s) -> System.out.println(s));
System.out.println(“———————added”);
}
}
});

this.setSize(600, 450);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public String openFileDialog() {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
System.out.println(“openFile”);
String selectedFilename = fileChooser.getSelectedFile().getAbsolutePath().toString();
System.out.println(selectedFilename);
return selectedFilename;
}
else {
System.out.println(“file not opened”);
return null;
}
}

public String saveFileDialog() {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showSaveDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
System.out.println(“saveFile”);
String selectedFilename = fileChooser.getSelectedFile().getAbsolutePath().toString();
System.out.println(selectedFilename);
return selectedFilename;
}
else {
System.out.println(“file not selected”);
return null;
}
}

// load CSV
public ArrayList<Person> loadCSV(String filename)
{
ArrayList<Person> pList = new ArrayList<Person>();
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
System.out.println(“file import: ” + filename);

String line = “”;
String delimiter = “,”;

while ((line = br.readLine()) != null) {
// use comma as separator
String[] items = line.split(delimiter);
String name = items[0];
int age = Integer.parseInt(items[1]);
double weight = Double.parseDouble(items[2]);
double height = Double.parseDouble(items[3]);
Gender gender = items[4].equals(“FEMALE”) ? Gender.FEMALE : Gender.MALE;

// add Person into List
Person p = new Person(name, age, weight, height, gender);
//System.out.println(p);
pList.add(p);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(“load successfully”);
return pList;
}

// save CSV
public void saveCSV(String path, ArrayList<Person> pList)
{
FileWriter fw;
try {
System.out.println(“file save: ” + path);

fw = new FileWriter(path);
for (Person p : pList) {
System.out.println(p);
fw.append(p.toString() + “\n”);
}
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}

public static void main(String args[])
{
new PersonTableFrame(); // data table
}

}

PointLib & ShapeDrawing

1. create a package (PointLib)

1.1 Point 클래스를 추가한다.
PointLib

 

2. create a package (ShapeApp)

ShapeApp

2.1. RandomShape 클래스를 추가한다.

 

package ShapeApp;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;

public class RandomShape {
Shape shape;
Color color;

RandomShape(Shape s, Color c) {
shape = s;
color = c;
}

public Shape getShape() {
return shape;
}

public void draw(Graphics2D g) {
g.setColor(color);
g.fill(shape);
}

boolean contains(int x, int y) {
return shape.contains((double) x, (double) y);
}

void translate(int x, int y) {
if (shape instanceof Polygon) {
Polygon p = (Polygon) shape;
p.translate(x, y);
}
else if (shape instanceof Rectangle) {
Rectangle r = (Rectangle) shape;
r.translate(x, y);
}
else if (shape instanceof Ellipse2D) {
Ellipse2D e = (Ellipse2D) shape;
e.setFrame((double) x, (double) y, e.getWidth(), e.getHeight());
}
}
}

2.2. RandomShapeFactory 클래스를 추가한다.

package ShapeApp;

import java.awt.Color;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;
import java.util.Random;

import PointLib.Point;

public class RandomShapeFactory {

private static Random rand = new Random();

public static Color randomColor() {
float r = rand.nextFloat();
float g = rand.nextFloat();
float b = rand.nextFloat();
return new Color(r, g, b);
}

public static int randomInt(int min, int max) {
return rand.nextInt(max-min) + min;
}

public static RandomShape getInstance(Point center) {
int shapeType = rand.nextInt() % 3;
System.out.println(“ShapeType=” + shapeType);
switch (shapeType) {
case 1:
{
System.out.println(“Triangle”);
int size = randomInt(20, 30);
Polygon triangle = new Polygon();
triangle.addPoint((int) center.getX(), (int) center.getY());
triangle.addPoint((int) (center.getX()-size), (int) (center.getY()+size));
triangle.addPoint((int) (center.getX()+size), (int) (center.getY()+size));
RandomShape s = new RandomShape(triangle, randomColor());
return s;
}

case 2:
{
System.out.println(“Rectangle”);
Shape rectangle = new Rectangle((int) center.getX(), (int) center.getY(), randomInt(50, 60), randomInt(50, 60));
RandomShape s= new RandomShape(rectangle, randomColor());
return s;
}

default:
{
System.out.println(“Oval”);
Shape oval = new Ellipse2D.Double(center.getX(), center.getY(), randomInt(40, 50), randomInt(30, 40));
RandomShape s= new RandomShape(oval, randomColor());
return s;
}
}
}
}

2.3. ShapeDrawing 클래스를 추가한다.

package ShapeApp;

import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.util.*;
import java.awt.event.*;

import PointLib.Point;

// ShapeDrawing
public class ShapeDrawing extends JFrame {
ShapeDrawingPanel polyCanvas = new ShapeDrawingPanel();

public static void main(String[] args) {
    new ShapeDrawing();
}

public ShapeDrawing() {
super(“Shape Drawing Frame”);

setBounds(10, 10, 350, 350);
setResizable(false);
setVisible(true);

polyCanvas.setPreferredSize(new Dimension(300, 300));
this.add(polyCanvas);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

private class ShapeDrawingPanel extends JPanel implements MouseListener, MouseMotionListener
{
int lastX, lastY;
boolean dragging = false;

ArrayList<RandomShape> shapes = new ArrayList<RandomShape>();
RandomShape selectedShape = null;

public ShapeDrawingPanel()
{
System.out.println(“ShapeDrawingPanel”);
addMouseListener(this);
addMouseMotionListener(this);
}

@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

for (RandomShape s : shapes)
s.draw(g2);
}

RandomShape findShape(int x, int y)
{
RandomShape s = null;
for (int i = shapes.size() – 1; i >= 0; i–) {
s = (RandomShape) shapes.get(i);
if (s.contains(x, y)) {
System.out.println(“Selected”);
return s;
}
}
return null;
}

public void mouseDragged(MouseEvent e) {
if (dragging == true) {
if (selectedShape.getShape() instanceof Ellipse2D)
selectedShape.translate(e.getX(), e.getY());
else {
int deltaX = e.getX() – lastX;
int deltaY = e.getY() – lastY;
System.out.println(“x = ” + deltaX + ” y = ” + deltaY);
selectedShape.translate(deltaX, deltaY);
lastX = e.getX();
lastY = e.getY();
}
repaint();
}
}

public void mouseMoved(MouseEvent e) {
}

public void mouseClicked(MouseEvent e) {
}

public void mousePressed(MouseEvent e) {
selectedShape = findShape(e.getX(), e.getY());
if (selectedShape != null) {
dragging = true;
lastX = e.getX();
lastY = e.getY();
}
else {
System.out.println(“Pressed”);
RandomShape s = RandomShapeFactory.getInstance(new Point((double) e.getX(), (double) e.getY()));
shapes.add(s);
repaint(); // calls paintComponent()
}
}

public void mouseReleased(MouseEvent e) {
if (dragging == true) {
dragging = false;
selectedShape = null;
}
}

public void mouseEntered(MouseEvent e) {
}

public void mouseExited(MouseEvent e) {
}
}
}

ShapeMaker

import java.awt.*;
import java.awt.geom.*;
import java.util.ArrayList;
import javax.swing.*;

public class ShapeMaker extends JFrame {

public static void main(String[] args) {
// TODO Auto-generated method stub
new ShapeMaker();
}

public ShapeMaker()
{
setSize(300, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new ShapeComponent());
setVisible(true);
}

private class ShapeComponent extends JComponent {
ArrayList<Shape> shapes = new ArrayList<Shape>();

public ShapeComponent() {
Shape s = new Rectangle2D.Float(10, 10, 60, 80);
shapes.add(s);

s = new RoundRectangle2D.Float(110, 10, 80, 80, 10, 10);
shapes.add(s);

s = new Ellipse2D.Float(10, 110, 80, 80);
shapes.add(s);

s = new Arc2D.Float(10, 210, 80, 80, 90, 90, Arc2D.OPEN);
shapes.add(s);

s = new Arc2D.Float(110, 210, 80, 80, 0, 180, Arc2D.CHORD);
shapes.add(s);

s = new Arc2D.Float(210, 210, 80, 80, 45, 90, Arc2D.PIE);
shapes.add(s);
}

public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(Color.LIGHT_GRAY);
for (int i = 0; i < getSize().width; i += 10) {
g2.draw(new Line2D.Float(i, 0, i, getSize().height));
}
for (int i = 0; i < getSize().height; i += 10) {
g2.draw(new Line2D.Float(0, i, getSize().width, i));
}
g2.setColor(Color.BLACK);
for (Shape s : shapes) {
g2.draw(s);
}
}
}
}

KoreaMapViewer

KoreaMapViewer

1. Download JMapViewer-2.0
2. Set CLASSPATH (in system environment variables) ./;C:\JMapViewer-2.0\JMapViewer.jar;C:\JMapViewer-2.0\JMapViewer_src.jar;C:\JMapViewer-2.0\JMapViewer_Demo.jar

& compile Demo.java (src)

javac-classpath

3. or, create a Java Project (KoreaMapViewer) in Eclipse

& create a new folder (lib) & add *.jar

& Configure Build Path & Add JARs

& compile Demo.java (src)

eclipse-configure-buildpath

eclipse-add-jars

EventHandler

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Button1Listener implements ActionListener { // (1) 독립적 이벤트 클래스

public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
button.setText(“버튼 1이 눌려졌습니다”);
}

}

class MyFrame extends JFrame implements ActionListener { // (3) 인터페이스 구현
JButton b1;
JButton b2;
JButton b3;
JButton b4;
JButton b5;

private class Button2Listener implements ActionListener { // (2) 내부 이벤트 클래스

public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if (button == b2) {
b1.setText(“버튼2 이 눌려졌습니다”);
b2.setText(“버튼2 이 눌려졌습니다”);
b3.setText(“버튼2 이 눌려졌습니다”);
}
}

}

public MyFrame() {
setTitle(“Absolute Position Test”);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);

JPanel p = new JPanel();
p.setLayout(null); // 절대위치크기 지정
b1 = new JButton(“Button #1”);
p.add(b1);
b2 = new JButton(“Button #2”);
p.add(b2);
b3 = new JButton(“Button #3”);
p.add(b3);
b4 = new JButton(“Button #4”);
p.add(b4);
b5 = new JButton(“Button #5”);
p.add(b5);
b1.setBounds(20, 5, 95, 30); // 절대위치크기 지정
b2.setBounds(55, 45, 105, 70); // 절대위치크기 지정
b3.setBounds(180, 15, 105, 90); // 절대위치크기 지정
b4.setBounds(80, 120, 105, 40); // 절대위치크기 지정
b5.setBounds(20, 170, 200, 30); // 절대위치크기 지정
add(p);

b1.addActionListener(new Button1Listener()); // (1) 독립적 이벤트 클래스 사용
b2.addActionListener(new Button2Listener()); // (2) 내부 이벤트 클래스 사용
b3.addActionListener(this);  // (3) 인터페이스 구현
b4.addActionListener(new ActionListener() { // (4) 무명 이벤트 클래스 사용
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if (button == b4) {
b1.setText(“버튼4 이 눌려졌습니다”);
b2.setText(“버튼4 이 눌려졌습니다”);
b3.setText(“버튼4 이 눌려졌습니다”);
b4.setText(“버튼4 이 눌려졌습니다”);
}
}
});
b5.addActionListener(e -> { // (5) lambda 사용
b1.setText(“버튼5 이 눌려졌습니다”);
b2.setText(“버튼5 이 눌려졌습니다”);
b3.setText(“버튼5 이 눌려졌습니다”);
b4.setText(“버튼5 이 눌려졌습니다”);
b5.setText(“버튼5 이 눌려졌습니다”);
});

setVisible(true);
}

public void actionPerformed(ActionEvent e) { // (3) 인터페이스 구현

JButton button = (JButton) e.getSource();
if (button == b3) {
b1.setText(“버튼3 이 눌려졌습니다”);
b2.setText(“버튼3 이 눌려졌습니다”);
b3.setText(“버튼3 이 눌려졌습니다”);
}

}

}

public class AbsolutePositionTest {
public static void main(String args[]) {
MyFrame f = new MyFrame();
}
}

Equals & Contains

import java.util.*;

class Person implements Comparable<Person>
{
private static int count = 0;   // static (class) variables

protected String name;    // instance variables
protected int age;        // instance variables

public Person()
{
//System.out.println(“Person Constructor”); // this(“”, 0); error: call to this must be first statemenht in constructor
this(“”, 0);
}

public Person(String name, int age)
{
count++;
this.name = name;
this.age = age;
}

public Person(Person other)
{
this(other.name, other.age);
}

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

public int getAge()
{
return age;
}

public void setAge(int age)
{
this.age = age;
}

@Override
public boolean equals(Object other)                             // Object.equals overriding
{
if (other instanceof Person) {
Person that = (Person) other;
return that.canEqual(this) && this.getName().equals(that.getName()) && this.getAge() == that.getAge();
}
return false;
}

@Override
public int hashCode() {
return (41 * getName().hashCode() + getAge());
}

public boolean canEqual(Object other) {
return (other instanceof Person);
}

@Override
public String toString()                                        // Object.toString() overriding
{
return “Person Name: ” + name + ” Age: ” + age;
}

public void print()                                             // instance methods
{
System.out.println(“Person Name: ” + name + ” Age: ” + age);
}

public void set(String name, int age)
{
this.name = name;
this.age = age;
}

public void set(Person other)
{
this.name = other.name;
this.age = other.age;
}

public Person clone()
{
Person p = new Person(this.name, this.age);
return p;
}

public static void printCount()          // static (class) methods
{
System.out.println(“Person Count: ” + count);
}

public static int getCount() { return count; }                  // static (class) methods
public static void setCount(int value) { count = value; }                  // static (class) methods

public int compareTo(Person other)
    {
      String thisName = this.getName().toUpperCase();
      String otherName = ((Person)other).getName().toUpperCase();

      //ascending order
      return thisName.compareTo(otherName);
      //descending order
      //return otherName.compareTo(thisName);
    }

public static Comparator<Person> AgeComparator
                          = new Comparator<Person>() {

     public int compare(Person p1, Person p2) {

       int age1 = p1.getAge();
       int age2 = p2.getAge();

       //ascending order
       return age1 – age2;

       //descending order
       //return age2 – age1;
     }

};

}

///////////////////////////////////////////////////////////////////////////////////////

class Student extends Person
{
private static int count = 0;   // static (class) variables
protected int id;

public Student()
{
id = 5208;
}

public Student(String name, int age, int id)
{
super(name, age);
this.id = id;
count++;
}

public int getID()
{
return id;
}

public void setID(int id)
{
this.id = id;
}

@Override
public boolean equals(Object other)                             // Object.equals overriding
{
if (other instanceof Student) {
Student that = (Student) other;
return that.canEqual(this) && this.getName().equals(that.getName()) && this.getAge() == that.getAge() && this.getID() == that.getID();
}
return false;
}

@Override
public int hashCode() {
return (41 * super.hashCode() + getID());
}

public boolean canEqual(Object other) {
return (other instanceof Student);
}

@Override
public String toString() // Object.toString() overriding
{
return “Student Name: ” + name + ” Age: ” + age + ” ID: ” + id;
}

public void superPrint()
{
super.print();
}

public void print() // Person class print() method overriding
{
System.out.println(“Student Name: ” + name + ” Age: ” + age + ” ID: ” + id);
}

public void set(String name, int age, int id)
{
super.set(name, age);
this.id = id;
}

public void set(String name, int age)
{
super.set(name, age);
}

public void set(Student other)
{
this.set(other.name, other.age, other.id);
}

public void set(Person other)
{
if (other instanceof Person)
super.set(other);
else
this.set((Student)other);
}

public Student clone()
{
Student s = new Student(this.name, this.age, this.id);
return s;
}

public static void printCount()         // static (class) methods
{
System.out.println(“Student Count: ” + count);
}

public static int getCount() { return count; }     // static (class) methods
public static void setCount(int value) { count = value; }       // static (class) methods

    public int compareTo(Student other)
    {
      String thisName = this.getName().toUpperCase();
      String otherName = ((Student)other).getName().toUpperCase();

      //ascending order
      return thisName.compareTo(otherName);
      //descending order
      //return otherName.compareTo(thisName);
    }

    public static Comparator<Student> AgeComparator
                          = new Comparator<Student>() {
     public int compare(Student p1, Student p2) {
       int age1 = p1.getAge();
       int age2 = p2.getAge();

       //ascending order
       return age1 – age2;

       //descending order
       //return age2 – age1;
     }

    };

    public static Comparator<Student> IDComparator
                          = new Comparator<Student>() {
     public int compare(Student p1, Student p2) {
       int id1 = p1.getID();
       int id2 = p2.getID();

       //ascending order
       return id1 – id2;

       //descending order
       //return id2 – id1;
     }

    };
}

class PersonStudentTest
{

public static void main(String[] args)
{

///////////////////////////////////////////////////////////////////////

Person jason1 = new Person(“Jason”, 10);
Person jason2 = new Person(“Jason”, 10);
Person jason3 = jason1;
Person jason4 = new Person(“Jason”, 20);

if (jason1 == jason2)
System.out.println(“jason1 == jason2”);
else
System.out.println(“jason1 != jason2”); //동일한 reference를 가리키지 않으므로 jason1 != jason2
if (jason1 == jason3)
System.out.println(“jason1 == jason3”); // 동일한 reference이므로 jason1 == jason3
else
System.out.println(“jason1 != jason3”);
if (jason1.equals(jason4))
System.out.println(“jason1 == jason4”);
else
System.out.println(“jason1 != jason4”); //동일한 reference를 가리키지 않으므로 jason1 != jason4

if (jason1.equals(jason2))
System.out.println(“jason1 equals to jason2”); // 내용이 같으므로  jason1 equals to jason2
else
System.out.println(“jason1 is not equal to jason2”);
if (jason1.equals(jason3))
System.out.println(“jason1 equals to jason3”); // 내용이 같으므로  jason1 equals to jason3
else
System.out.println(“jason1 is not equal to jason3”);
if (jason1.equals(jason4))
System.out.println(“jason1 equals jason4”);
else
System.out.println(“jason1 is not equal to jason4”); // 내용이 다르므로 jason1 is not equal to jason4

///////////////////////////////////////////////////////////////////////
Student john1 = new Student(“John”, 10, 100);
Student john2 = new Student(“John”, 10, 100);
Student john3 = john1;
Student john4 = new Student(“John”, 20, 100);
if (john1.equals(john2))
System.out.println(“john1 equals to john2”); // 내용이 같으므로  john1 equals to john2
else
System.out.println(“john1 is not equal to john2”);

if (john1.equals(john3))
System.out.println(“john1 equals to john3”); // 내용이 같으므로 jogn1 equals to john3
else
System.out.println(“john1 is not equal to john3”);

if (john1.equals(john4))
System.out.println(“john1 equals to john4”);
else
System.out.println(“john1 is not equal to john4”); // 내용이 다르므로 john1 is not equal to john4

Set<Student> sList5 = new HashSet<Student>();
sList5.add(john1);
        sList5.add(john2);
        sList5.add(john3);
        sList5.add(john4);
        sList5.forEach((s) -> System.out.println(s));
System.out.println(“sList5 contains john1 Student(\”John\”, 10, 100): ” + sList5.contains(john1));
System.out.println(“sList5 contains john2 Student(\”John\”, 10, 100): ” + sList5.contains(john2));
System.out.println(“sList5 contains john3 Student(\”John\”, 10, 100): ” + sList5.contains(john3));
System.out.println(“sList5 contains john4 Student(\”John\”, 20, 100):: ” + sList5.contains(john4));
System.out.println(“sList5 contains Student(\”John\”, 20, 100): ” + sList5.contains(new Student(“John”, 20, 100)));
System.out.println(“sList5 contains Student(\”John\”, 20, 200): ” + sList5.contains(new Student(“John”, 20, 200)));

Hashtable<Integer, Student> sList6 = new Hashtable<Integer, Student>();
sList6.put(1, john1);
        sList6.put(2, john2);
        sList6.put(3, john3);
        sList6.put(4, john4);
sList6.forEach((i, s) -> System.out.println(s));
System.out.println(“sList5 contains john1 Student(\”John\”, 10, 100): ” + sList5.contains(john1));
System.out.println(“sList5 contains john2 Student(\”John\”, 10, 100): ” + sList5.contains(john2));
System.out.println(“sList5 contains john3 Student(\”John\”, 10, 100): ” + sList5.contains(john3));
System.out.println(“sList5 contains john4 Student(\”John\”, 20, 100):: ” + sList5.contains(john4));
System.out.println(“sList5 contains Student(\”John\”, 20, 100): ” + sList5.contains(new Student(“John”, 20, 100)));
System.out.println(“sList5 contains Student(\”John\”, 20, 200): ” + sList5.contains(new Student(“John”, 20, 200)));

  }

}

Comparable & Comparator Interface

PersonStudentInterface

/////////////////////////////////

import java.util.*;

class Person implements Comparable<Person>
{
private static int count = 0;   // static (class) variables

protected String name;    // instance variables
protected int age;        // instance variables

public Person()
{
//System.out.println(“Person Constructor”); // this(“”, 0); error: call to this must be first statemenht in constructor
this(“”, 0);
}

public Person(String name, int age)
{
count++;
this.name = name;
this.age = age;
}

public Person(Person other)
{
this(other.name, other.age);
}

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

public int getAge()
{
return age;
}

public void setAge(int age)
{
this.age = age;
}

@Override
public boolean equals(Object other)                             // Object.equals overriding
{
if (other instanceof Person) {
Person that = (Person) other;
return that.canEqual(this) && this.getName().equals(that.getName()) && this.getAge() == that.getAge();
}
return false;
}

@Override
public int hashCode() {
return (41 * getName().hashCode() + getAge());
}

public boolean canEqual(Object other) {
return (other instanceof Person);
}

@Override
public String toString()                                        // Object.toString() overriding
{
return “Person Name: ” + name + ” Age: ” + age;
}

public void print()                                             // instance methods
{
System.out.println(“Person Name: ” + name + ” Age: ” + age);
}

public void set(String name, int age)
{
this.name = name;
this.age = age;
}

public void set(Person other)
{
this.name = other.name;
this.age = other.age;
}

public Person clone()
{
Person p = new Person(this.name, this.age);
return p;
}

public static void printCount()          // static (class) methods
{
System.out.println(“Person Count: ” + count);
}

public static int getCount() { return count; }                  // static (class) methods
public static void setCount(int value) { count = value; }                  // static (class) methods

public int compareTo(Person other)
    {
      String thisName = this.getName().toUpperCase();
      String otherName = ((Person)other).getName().toUpperCase();

      //ascending order
      return thisName.compareTo(otherName);
      //descending order
      //return otherName.compareTo(thisName);
    }

public static Comparator<Person> AgeComparator
                          = new Comparator<Person>() {

     public int compare(Person p1, Person p2) {

       int age1 = p1.getAge();
       int age2 = p2.getAge();

       //ascending order
       return age1 – age2;

       //descending order
       //return age2 – age1;
     }

};

}

///////////////////////////////////////////////////////////////////////////////////////

class Student extends Person
{
private static int count = 0;   // static (class) variables
protected int id;

public Student()
{
id = 5208;
}

public Student(String name, int age, int id)
{
super(name, age);
this.id = id;
count++;
}

public int getID()
{
return id;
}

public void setID(int id)
{
this.id = id;
}

@Override
public boolean equals(Object other)                             // Object.equals overriding
{
if (other instanceof Student) {
Student that = (Student) other;
return that.canEqual(this) && this.getName().equals(that.getName()) && this.getAge() == that.getAge() && this.getID() == that.getID();
}
return false;
}

@Override
public int hashCode() {
return (41 * super.hashCode() + getID());
}

public boolean canEqual(Object other) {
return (other instanceof Student);
}

@Override
public String toString() // Object.toString() overriding
{
return “Student Name: ” + name + ” Age: ” + age + ” ID: ” + id;
}

public void superPrint()
{
super.print();
}

public void print() // Person class print() method overriding
{
System.out.println(“Student Name: ” + name + ” Age: ” + age + ” ID: ” + id);
}

public void set(String name, int age, int id)
{
super.set(name, age);
this.id = id;
}

public void set(String name, int age)
{
super.set(name, age);
}

public void set(Student other)
{
this.set(other.name, other.age, other.id);
}

public void set(Person other)
{
if (other instanceof Person)
super.set(other);
else
this.set((Student)other);
}

public Student clone()
{
Student s = new Student(this.name, this.age, this.id);
return s;
}

public static void printCount()         // static (class) methods
{
System.out.println(“Student Count: ” + count);
}

public static int getCount() { return count; }     // static (class) methods
public static void setCount(int value) { count = value; }       // static (class) methods

    public int compareTo(Student other)
    {
      String thisName = this.getName().toUpperCase();
      String otherName = ((Student)other).getName().toUpperCase();

      //ascending order
      return thisName.compareTo(otherName);
      //descending order
      //return otherName.compareTo(thisName);
    }

    public static Comparator<Student> AgeComparator
                          = new Comparator<Student>() {
     public int compare(Student p1, Student p2) {
       int age1 = p1.getAge();
       int age2 = p2.getAge();

       //ascending order
       return age1 – age2;

       //descending order
       //return age2 – age1;
     }

    };

    public static Comparator<Student> IDComparator
                          = new Comparator<Student>() {
     public int compare(Student p1, Student p2) {
       int id1 = p1.getID();
       int id2 = p2.getID();

       //ascending order
       return id1 – id2;

       //descending order
       //return id2 – id1;
     }

    };
}

 

class PersonStudentTest
{

public static void print(Object[] array) {
for(Object o : array) {
System.out.println(o);
}
}

public static void main(String[] args)
{

///////////////////////////////////////////////////////////////////////

Student[] sList = new Student[3];
sList[0] = new Student(“Kevin”, 0, 222);
sList[1] = new Student(“Jason”, 1, 333);
sList[2] = new Student(“John”, 2, 111);

System.out.println(“STUDENT SORT BY NAME (DEFAULT)!!!”);
Arrays.sort(sList);
print(sList);

System.out.println(“STUDENT SORT by AGE!!!”);
Arrays.sort(sList, Student.AgeComparator);
print(sList);

System.out.println(“STUDENT SORT by ID!!!”);
Arrays.sort(sList, Student.IDComparator);
print(sList);

///////////////////////////////////////////////////////////////////////
Student[] sList2 = new Student[3];
sList2[0] = new Student(“Kevin”, 0, 222);
sList2[1] = new Student(“Jason”, 1, 333);
sList2[2] = new Student(“John”, 2, 111);

System.out.println(“STUDENT SORT BY NAME (anonymous method)!!!”);
Arrays.sort(sList2, new Comparator<Student>() {
            public int compare(Student s1, Student s2) {
                return s1.getName().toUpperCase().compareTo(s2.getName().toUpperCase());
            }
        });
print(sList2);

System.out.println(“STUDENT SORT by AGE (anonymous method)!!!”);
Arrays.sort(sList2, new Comparator<Student>() {
            public int compare(Student s1, Student s2) {
                return s1.getAge() – s2.getAge();
            }
        });
print(sList2);

System.out.println(“STUDENT SORT by ID (anonymous method)!!!”);
Arrays.sort(sList2, new Comparator<Student>() {
            public int compare(Student s1, Student s2) {
                return s1.getID() – s2.getID();
            }
        });
print(sList2);

///////////////////////////////////////////////////////////////////////
Student[] sList3 = sList2;

System.out.println(“STUDENT SORT BY NAME (lambda)!!!”);
Arrays.sort(sList3, (Student ss1, Student ss2) ->
                ss1.getName().compareTo(ss2.getName())
        );
Arrays.stream(sList3).forEach((s) -> System.out.println(s));

System.out.println(“STUDENT SORT by AGE (lambda)!!!”);
Arrays.sort(sList3, (Student ss1, Student ss2) ->
                Integer.compare(ss1.getAge(), ss2.getAge())
        );
Arrays.stream(sList3).forEach((s) -> System.out.println(s));

System.out.println(“STUDENT SORT by ID (lambda)!!!”);
Arrays.sort(sList3, (Student ss1, Student ss2) ->
                Integer.compare(ss1.getID(), ss2.getID())
        );
Arrays.stream(sList3).forEach((s) -> System.out.println(s));

///////////////////////////////////////////////////////////////////////
List<Student> sList4 = new ArrayList<Student>();
sList4.add(new Student(“Kevin”, 0, 222));
        sList4.add(new Student(“Jason”, 1, 333));
        sList4.add(new Student(“John”, 2, 111));

System.out.println(“STUDENTLIST SORT BY NAME (lambda)!!!”);
sList4.sort((Student ss1, Student ss2) ->
                ss1.getName().compareTo(ss2.getName())
        );
sList4.forEach((s) -> System.out.println(s));

System.out.println(“STUDENTLIST SORT by AGE (lambda)!!!”);
sList4.sort((Student ss1, Student ss2) ->
                ss1.getAge() – ss2.getAge()
        );
sList4.forEach((s) -> System.out.println(s));

System.out.println(“STUDENTLIST SORT by ID (lambda)!!!”);
sList4.sort((Student ss1, Student ss2) ->
                ss1.getID() – ss2.getID()
        );
sList4.forEach((s) -> System.out.println(s));

}

}