Merge branch 'eugenp:master' into deepShallowCopy

This commit is contained in:
Neetika23
2023-10-21 20:23:16 +05:30
committed by GitHub
1738 changed files with 32150 additions and 7158 deletions
@@ -1,15 +0,0 @@
package reminderapplication;
import java.awt.GridBagConstraints;
import java.awt.Insets;
public class ConstraintsBuilder {
static GridBagConstraints constraint(int x, int y) {
final GridBagConstraints gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = x;
gridBagConstraints.gridy = y;
gridBagConstraints.insets = new Insets(5, 5, 5, 5);
return gridBagConstraints;
}
}
@@ -1,194 +0,0 @@
package reminderapplication;
import static reminderapplication.ConstraintsBuilder.*;
import java.awt.GridBagLayout;
import java.awt.HeadlessException;
import java.lang.reflect.InvocationTargetException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class EditReminderFrame extends JFrame {
private static Timer TIMER = new Timer();
private final TimeReminderApplication reminderApplication;
private final JLabel reminderTextLabel;
private final JLabel repeatPeriodLabel;
private final JLabel setDelayLabel;
private final JComboBox<Integer> delay;
private final JComboBox<Integer> period;
private final JButton cancelButton;
private final JButton okButton;
private final JTextField textField;
private final JLabel delaysLabel;
private final JLabel periodLabel;
private final int reminderIndex;
public EditReminderFrame(TimeReminderApplication reminderApp, String reminderText, int delayInSeconds, int periodInSeconds, int index) throws HeadlessException {
this.reminderApplication = reminderApp;
reminderIndex = index;
textField = createTextField(reminderText);
delay = createDelayComboBox(delayInSeconds);
period = createPeriodComboBox(periodInSeconds);
cancelButton = createCancelButton();
okButton = createOkButton();
reminderTextLabel = createReminderTextLabel();
repeatPeriodLabel = createRepeatPeriodLabel();
setDelayLabel = createSetDelayLabel();
delaysLabel = createDelaysLabel();
periodLabel = createPeriodLabel();
configureVisualRepresentation();
configureActions();
}
private void configureActions() {
updateReminder();
}
private void configureVisualRepresentation() {
configureFrame();
setLocationRelativeTo(null);
setLayout(new GridBagLayout());
add(reminderTextLabel, constraint(0,0));
add(repeatPeriodLabel, constraint(1,0));
add(setDelayLabel, constraint(2,0));
add(textField, constraint(0, 1));
add(delay, constraint(1, 1));
add(period, constraint(2, 1));
add(delaysLabel, constraint(1,3));
add(periodLabel, constraint(2,3));
add(okButton, constraint(1, 4));
add(cancelButton, constraint(2, 4));
pack();
setVisible(true);
}
private void configureFrame() {
setTitle("Set Reminder");
setName("Set Reminder");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
private static JLabel createSetDelayLabel() {
return createLabel("Set Delay", "Set Delay Label");
}
private static JLabel createRepeatPeriodLabel() {
return createLabel("Set Period", "Set Repeat Period Label");
}
private static JLabel createReminderTextLabel() {
return createLabel("Reminder Text", "Reminder Text Label");
}
private JLabel createPeriodLabel() {
return createLabel("0", "Period label");
}
private JLabel createDelaysLabel() {
return createLabel("30", "Delays Label");
}
private JComboBox<Integer> createPeriodComboBox(final int periodInSeconds) {
final JComboBox<Integer> comboBox = new JComboBox<>(new DefaultComboBoxModel<>(new Integer[]{0, 5, 10, 20}));
comboBox.setSelectedItem(periodInSeconds);
comboBox.setName("set Period");
comboBox.addActionListener(e -> periodLabel.setText(comboBox.getSelectedItem().toString()));
return comboBox;
}
private JComboBox<Integer> createDelayComboBox(final int delayInSeconds) {
final JComboBox<Integer> comboBox = new JComboBox<>(new DefaultComboBoxModel<>(new Integer[]{30, 25, 15, 5}));
comboBox.setSelectedItem(delayInSeconds);
comboBox.setName("set Delay");
comboBox.addActionListener(e -> delaysLabel.setText(comboBox.getSelectedItem().toString()));
return comboBox;
}
private JTextField createTextField(final String reminderText) {
final JTextField textField = new JTextField(20);
textField.setName("Field");
textField.setText(reminderText);
return textField;
}
private JButton createOkButton() {
final JButton button = new JButton("ok");
button.setName("OK");
return button;
}
private void updateReminder() {
okButton.addActionListener(e -> this.dispose());
okButton.addActionListener(e -> {
final int periodInSeconds = getTimeInSeconds(period);
final int delayInSeconds = getTimeInSeconds(delay);
final Reminder reminder = new Reminder(textField.getText(), delayInSeconds, periodInSeconds);
((DefaultListModel<Reminder>) reminderApplication.getReminders()).set(reminderIndex, reminder);
});
okButton.addActionListener(e -> scheduleReminder(textField, delay, period));
}
private void scheduleReminder(final JTextField textField, final JComboBox<Integer> delay, final JComboBox<Integer> period) {
final int periodInSeconds = getTimeInSeconds(period);
if (periodInSeconds == 0)
scheduleNonRepeatedReminder(textField, delay);
else
scheduleRepeatedReminder(textField, delay, period);
}
private void scheduleRepeatedReminder(final JTextField textField, final JComboBox<Integer> delay, final JComboBox<Integer> period) {
final int delayInSeconds = getTimeInSeconds(delay);
final int periodInSeconds = getTimeInSeconds(period);
final TimerTask timerTask = getTimerTask(textField.getText(), delayInSeconds, periodInSeconds);
TIMER.schedule(timerTask, TimeUnit.SECONDS.toMillis(delayInSeconds), TimeUnit.SECONDS.toMillis(periodInSeconds));
}
private void scheduleNonRepeatedReminder(final JTextField textField, final JComboBox<Integer> delay) {
final int delayInSeconds = getTimeInSeconds(delay);
final int periodInSeconds = 0;
final TimerTask timerTask = getTimerTask(textField.getText(), delayInSeconds, periodInSeconds);
TIMER.schedule(timerTask, TimeUnit.SECONDS.toMillis(delayInSeconds));
}
private int getTimeInSeconds(final JComboBox<Integer> comboBox) {
if (comboBox != null && comboBox.getSelectedItem() != null)
return ((Integer) comboBox.getSelectedItem());
else
return 0;
}
private TimerTask getTimerTask(final String reminderText, final Integer delayInSeconds, final Integer periodInSeconds) {
return new TimerTask() {
@Override
public void run() {
new ReminderPopupFrame(reminderApplication, reminderText, delayInSeconds, periodInSeconds);
}
};
}
private JButton createCancelButton() {
final JButton button = new JButton("cancel");
button.setName("Cancel");
button.addActionListener(e -> this.dispose());
return button;
}
private static JLabel createLabel(final String text, final String name) {
JLabel label = new JLabel(text);
label.setName(name);
return label;
}
}
@@ -1,33 +0,0 @@
package reminderapplication;
public class Reminder {
private static String REMINDER_FORMAT = "Reminder Text: %s; Delay: %d; Period: %d;";
private final String name;
private final int delay;
private final int period;
public Reminder(final String name, final int delay, final int period) {
this.name = name;
this.delay = delay;
this.period = period;
}
public String getName() {
return name;
}
public int getDelay() {
return delay;
}
public int getPeriod() {
return period;
}
@Override
public String toString() {
return REMINDER_FORMAT.formatted(name, delay, period);
}
}
@@ -1,186 +0,0 @@
package reminderapplication;
import static reminderapplication.ConstraintsBuilder.*;
import java.awt.GridBagLayout;
import java.awt.HeadlessException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class ReminderFrame extends JFrame {
private static Timer TIMER = new Timer();
private final TimeReminderApplication reminderApplication;
private final JLabel reminderTextLabel;
private final JLabel repeatPeriodLabel;
private final JLabel setDelayLabel;
private final JComboBox<Integer> delay;
private final JComboBox<Integer> period;
private final JButton cancelButton;
private final JButton okButton;
private final JTextField textField;
private final JLabel delaysLabel;
private final JLabel periodLabel;
public ReminderFrame(TimeReminderApplication reminderApp) throws HeadlessException {
this.reminderApplication = reminderApp;
textField = createTextField();
delay = createDelayComboBox();
period = createPeriodComboBox();
cancelButton = createCancelButton();
okButton = createOkButton();
reminderTextLabel = createReminderTextLabel();
repeatPeriodLabel = createRepeatPeriodLabel();
setDelayLabel = createSetDelayLabel();
delaysLabel = createDelaysLabel();
periodLabel = createPeriodLabel();
configureVisualRepresentation();
configureActions();
}
private void configureActions() {
createNewReminder();
}
private void configureVisualRepresentation() {
configureFrame();
setLocationRelativeTo(null);
setLayout(new GridBagLayout());
add(reminderTextLabel, constraint(0,0));
add(repeatPeriodLabel, constraint(1,0));
add(setDelayLabel, constraint(2,0));
add(textField, constraint(0, 1));
add(delay, constraint(1, 1));
add(period, constraint(2, 1));
add(delaysLabel, constraint(1,3));
add(periodLabel, constraint(2,3));
add(okButton, constraint(1, 4));
add(cancelButton, constraint(2, 4));
pack();
setVisible(true);
}
private void configureFrame() {
setTitle("Set Reminder");
setName("Set Reminder");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
private static JLabel createSetDelayLabel() {
return createLabel("Set Delay", "Set Delay Label");
}
private static JLabel createRepeatPeriodLabel() {
return createLabel("Set Period", "Set Repeat Period Label");
}
private static JLabel createReminderTextLabel() {
return createLabel("Reminder Text", "Reminder Text Label");
}
private JLabel createPeriodLabel() {
return createLabel("0", "Period label");
}
private JLabel createDelaysLabel() {
return createLabel("30", "Delays Label");
}
private JComboBox<Integer> createPeriodComboBox() {
final JComboBox<Integer> comboBox = new JComboBox<>(new DefaultComboBoxModel<>(new Integer[]{0, 5, 10, 20}));
comboBox.setName("set Period");
comboBox.addActionListener(e -> periodLabel.setText(comboBox.getSelectedItem().toString()));
return comboBox;
}
private JComboBox<Integer> createDelayComboBox() {
final JComboBox<Integer> comboBox = new JComboBox<>(new DefaultComboBoxModel<>(new Integer[]{30, 25, 15, 5}));
comboBox.setName("set Delay");
comboBox.addActionListener(e -> delaysLabel.setText(comboBox.getSelectedItem().toString()));
return comboBox;
}
private JTextField createTextField() {
final JTextField textField = new JTextField(20);
textField.setName("Field");
return textField;
}
private JButton createOkButton() {
final JButton button = new JButton("ok");
button.setName("OK");
return button;
}
private void createNewReminder() {
okButton.addActionListener(e -> this.dispose());
okButton.addActionListener(e -> {
final int periodInSeconds = getTimeInSeconds(period);
final int delayInSeconds = getTimeInSeconds(delay);
final Reminder reminder = new Reminder(textField.getText(), delayInSeconds, periodInSeconds);
((DefaultListModel<Reminder>) reminderApplication.getReminders()).addElement(reminder);
});
okButton.addActionListener(e -> scheduleReminder(textField, delay, period));
}
private void scheduleReminder(final JTextField textField, final JComboBox<Integer> delay, final JComboBox<Integer> period) {
final int periodInSeconds = getTimeInSeconds(period);
if (periodInSeconds == 0)
scheduleNonRepeatedReminder(textField, delay);
else
scheduleRepeatedReminder(textField, delay, period);
}
private void scheduleRepeatedReminder(final JTextField textField, final JComboBox<Integer> delay, final JComboBox<Integer> period) {
final int delayInSeconds = getTimeInSeconds(delay) + 200;
final int periodInSeconds = getTimeInSeconds(period);
final TimerTask timerTask = getTimerTask(textField.getText(), delayInSeconds, periodInSeconds);
TIMER.schedule(timerTask, TimeUnit.SECONDS.toMillis(delayInSeconds), TimeUnit.SECONDS.toMillis(periodInSeconds));
}
private void scheduleNonRepeatedReminder(final JTextField textField, final JComboBox<Integer> delay) {
final int delayInSeconds = getTimeInSeconds(delay);
final int periodInSeconds = 0;
final TimerTask timerTask = getTimerTask(textField.getText(), delayInSeconds, periodInSeconds);
TIMER.schedule(timerTask, TimeUnit.SECONDS.toMillis(delayInSeconds));
}
private int getTimeInSeconds(final JComboBox<Integer> comboBox) {
if (comboBox != null && comboBox.getSelectedItem() != null)
return ((Integer) comboBox.getSelectedItem());
else
return 0;
}
private TimerTask getTimerTask(final String reminderText, final Integer delayInSeconds, final Integer periodInSeconds) {
return new TimerTask() {
@Override
public void run() {
new ReminderPopupFrame(reminderApplication, reminderText, delayInSeconds, periodInSeconds);
}
};
}
private JButton createCancelButton() {
final JButton button = new JButton("cancel");
button.setName("Cancel");
button.addActionListener(e -> this.dispose());
return button;
}
private static JLabel createLabel(final String text, final String name) {
JLabel label = new JLabel(text);
label.setName(name);
return label;
}
}
@@ -1,151 +0,0 @@
package reminderapplication;
import static reminderapplication.ConstraintsBuilder.*;
import java.awt.GridBagLayout;
import java.awt.HeadlessException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class ReminderPopupFrame extends JFrame {
private static final Timer TIMER = new Timer();
private final int AUTOMATIC_CLOSE_TIME_IN_SECONDS = 10;
private final TimeReminderApplication reminderApplication;
private final JLabel reminderTextLabel;
private final JLabel repeatPeriodLabel;
private final JLabel setDelayLabel;
private final JComboBox<Integer> delay;
private final JComboBox<Integer> period;
private final JButton cancelButton;
private final JButton okButton;
private final JTextField textField;
private final JLabel delaysLabel;
private final JLabel periodLabel;
public ReminderPopupFrame(TimeReminderApplication reminderApp, final String text, final Integer delayInSeconds, final Integer periodInSeconds) throws HeadlessException {
this.reminderApplication = reminderApp;
textField = createTextField(text);
delay = createDelayComboBox(delayInSeconds);
period = createPeriodComboBox(periodInSeconds);
cancelButton = createCancelButton();
okButton = createDisabledOkButton();
reminderTextLabel = createReminderTextLabel();
repeatPeriodLabel = createRepeatPeriodLabel();
setDelayLabel = createSetDelayLabel();
delaysLabel = createDelaysLabel();
periodLabel = createPeriodLabel();
configureVisualRepresentation();
configureActions();
}
private void configureActions() {
scheduleClosing();
}
private void scheduleClosing() {
final TimerTask timerTask = new TimerTask() {
@Override
public void run() {
ReminderPopupFrame.this.dispose();
}
};
TIMER.schedule(timerTask, TimeUnit.SECONDS.toMillis(AUTOMATIC_CLOSE_TIME_IN_SECONDS));
}
private void configureVisualRepresentation() {
configureFrame();
setLocationRelativeTo(null);
setLayout(new GridBagLayout());
add(reminderTextLabel, constraint(0,0));
add(repeatPeriodLabel, constraint(1,0));
add(setDelayLabel, constraint(2,0));
add(textField, constraint(0, 1));
add(delay, constraint(1, 1));
add(period, constraint(2, 1));
add(delaysLabel, constraint(1,3));
add(periodLabel, constraint(2,3));
add(okButton, constraint(1, 4));
add(cancelButton, constraint(2, 4));
pack();
setVisible(true);
}
private void configureFrame() {
setTitle("Set Reminder");
setName("Set Reminder");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
private static JLabel createSetDelayLabel() {
return createLabel("Set Delay", "Set Delay Label");
}
private static JLabel createRepeatPeriodLabel() {
return createLabel("Set Period", "Set Repeat Period Label");
}
private static JLabel createReminderTextLabel() {
return createLabel("Reminder Text", "Reminder Text Label");
}
private JLabel createPeriodLabel() {
return createLabel("0", "Period label");
}
private JLabel createDelaysLabel() {
return createLabel("30", "Delays Label");
}
private JComboBox<Integer> createPeriodComboBox(final Integer periodInSeconds) {
final JComboBox<Integer> comboBox = new JComboBox<>(new DefaultComboBoxModel<>(new Integer[]{0, 5, 10, 20}));
comboBox.setName("set Period");
comboBox.setSelectedItem(periodInSeconds);
comboBox.addActionListener(e -> periodLabel.setText(comboBox.getSelectedItem().toString()));
return comboBox;
}
private JComboBox<Integer> createDelayComboBox(Integer delay) {
final JComboBox<Integer> comboBox = new JComboBox<>(new DefaultComboBoxModel<>(new Integer[]{30, 25, 15, 5}));
comboBox.setSelectedItem(delay);
comboBox.setName("set Delay");
comboBox.addActionListener(e -> delaysLabel.setText(comboBox.getSelectedItem().toString()));
return comboBox;
}
private JTextField createTextField(final String text) {
final JTextField textField = new JTextField(20);
textField.setName("Field");
textField.setText(text);
return textField;
}
private JButton createDisabledOkButton() {
final JButton button = new JButton("ok");
button.setName("OK");
button.setEnabled(false);
return button;
}
private JButton createCancelButton() {
final JButton button = new JButton("cancel");
button.setName("Cancel");
button.addActionListener(e -> this.dispose());
return button;
}
private static JLabel createLabel(final String text, final String name) {
JLabel label = new JLabel(text);
label.setName(name);
return label;
}
}
@@ -5,7 +5,6 @@ This module contains articles about Java 11 core features
### Relevant articles
- [Guide To Java 8 Optional](https://www.baeldung.com/java-optional)
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
- [Guide to Java 8s Collectors](https://www.baeldung.com/java-8-collectors)
- [New Features in Java 11](https://www.baeldung.com/java-11-new-features)
- [Getting the Java Version at Runtime](https://www.baeldung.com/get-java-version-runtime)
- [Invoking a SOAP Web Service in Java](https://www.baeldung.com/java-soap-web-service)
+4 -26
View File
@@ -8,9 +8,9 @@
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
@@ -21,30 +21,8 @@
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source.version}</source>
<target>${maven.compiler.target.version}</target>
<compilerArgs>--enable-preview</compilerArgs>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>--enable-preview</argLine>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source.version>12</maven.compiler.source.version>
<maven.compiler.target.version>12</maven.compiler.target.version>
<java.version>17</java.version>
</properties>
</project>
@@ -19,19 +19,6 @@ public class SwitchUnitTest {
Assert.assertEquals(value, 2);
}
@Test
public void switchLocalVariable(){
var month = Month.AUG;
int i = switch (month){
case JAN,JUN, JUL -> 3;
case FEB,SEP, OCT, NOV, DEC -> 1;
case MAR,MAY, APR, AUG -> {
int j = month.toString().length() * 4;
break j;
}
};
Assert.assertEquals(12, i);
}
enum Month {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}
}
+4 -30
View File
@@ -8,39 +8,13 @@
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source.version}</source>
<target>${maven.compiler.target.version}</target>
<release>13</release>
<compilerArgs>--enable-preview</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.plugin.version}</version>
<configuration>
<argLine>--enable-preview</argLine>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source.version>13</maven.compiler.source.version>
<maven.compiler.target.version>13</maven.compiler.target.version>
<surefire.plugin.version>3.0.0-M3</surefire.plugin.version>
<java.version>17</java.version>
</properties>
</project>
@@ -7,7 +7,6 @@ import org.junit.Test;
public class SwitchExpressionsWithYieldUnitTest {
@Test
@SuppressWarnings("preview")
public void whenSwitchingOnOperationSquareMe_thenWillReturnSquare() {
var me = 4;
var operation = "squareMe";
@@ -8,7 +8,6 @@ public class TextBlocksUnitTest {
private static final String JSON_STRING = "{\r\n" + "\"name\" : \"Baeldung\",\r\n" + "\"website\" : \"https://www.%s.com/\"\r\n" + "}";
@SuppressWarnings("preview")
private static final String TEXT_BLOCK_JSON = """
{
"name" : "Baeldung",
@@ -25,7 +24,6 @@ public class TextBlocksUnitTest {
}
@SuppressWarnings("removal")
@Test
public void whenTextBlocks_thenFormattedWorksAsFormat() {
assertThat(TEXT_BLOCK_JSON.formatted("baeldung")
@@ -13,7 +13,6 @@ import org.junit.Test;
public class SwitchExpressionsUnitTest {
@Test
@SuppressWarnings ("preview")
public void whenSwitchingOverMonthJune_thenWillReturn3() {
var month = JUNE;
@@ -29,7 +28,6 @@ public class SwitchExpressionsUnitTest {
}
@Test
@SuppressWarnings ("preview")
public void whenSwitchingOverMonthAugust_thenWillReturn24() {
var month = AUGUST;
@@ -47,7 +45,6 @@ public class SwitchExpressionsUnitTest {
}
@Test
@SuppressWarnings ("preview")
public void whenSwitchingOverMonthJanuary_thenWillReturn3() {
Function<Month, Integer> func = (month) -> {
@@ -61,7 +58,6 @@ public class SwitchExpressionsUnitTest {
}
@Test
@SuppressWarnings ("preview")
public void whenSwitchingOverMonthAugust_thenWillReturn2() {
var month = AUGUST;
-1
View File
@@ -48,7 +48,6 @@
<properties>
<maven.compiler.release>14</maven.compiler.release>
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
<surefire.plugin.version>3.0.0-M3</surefire.plugin.version>
</properties>
+4 -31
View File
@@ -8,10 +8,9 @@
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
@@ -27,34 +26,8 @@
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<release>${maven.compiler.release}</release>
<compilerArgs>--enable-preview</compilerArgs>
<source>14</source>
<target>14</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.plugin.version}</version>
<configuration>
<argLine>--enable-preview</argLine>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.release>15</maven.compiler.release>
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
<surefire.plugin.version>3.0.0-M3</surefire.plugin.version>
<java.version>17</java.version>
</properties>
</project>
+1 -1
View File
@@ -4,4 +4,4 @@
- [Guide to mapMulti in Stream API](https://www.baeldung.com/java-mapmulti)
- [Collecting Stream Elements into a List in Java](https://www.baeldung.com/java-stream-to-list-collecting)
- [New Features in Java 16](https://www.baeldung.com/java-16-new-features)
- [Guide to Java 8 groupingBy Collector](https://www.baeldung.com/java-groupingby-collector)
- [Value-Based Classes in Java](https://www.baeldung.com/java-value-based-classes)
@@ -0,0 +1,54 @@
package com.baeldung.value_based_class;
import java.util.Objects;
import jdk.internal.ValueBased;
/**
* This class is written with the intention that it can serve as an example of
* what a Value-based class could be.
*/
@ValueBased
public final class Point {
private final int x;
private final int y;
private final int z;
private static Point ORIGIN = new Point(0, 0, 0);
private Point(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public static Point valueOfPoint(int x, int y, int z) {
// returns a cached instance if it is origin, or a new instance
if (isOrigin(x, y, z))
return ORIGIN;
return new Point(x, y, z);
}
@Override
public String toString() {
return "Point{" + "x=" + x + ", y=" + y + ", z=" + z + '}';
}
@Override
public boolean equals(Object other) {
if (other == null || getClass() != other.getClass())
return false;
Point point = (Point) other;
return x == point.x && y == point.y && z == point.z;
}
@Override
public int hashCode() {
return Objects.hash(x, y, z);
}
private static boolean isOrigin(int x, int y, int z) {
return x == 0 && y == 0 && z == 0;
}
}
@@ -0,0 +1,44 @@
package com.baeldung.value_based_class;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
public class ValueBasedClassUnitTest {
@Test
public void givenAutoboxedAndPrimitive_whenCompared_thenReturnEquals() {
List<Integer> list = new ArrayList<>();
list.add(1); // this is autoboxed
Assert.assertEquals(list.get(0), Integer.valueOf(1));
}
@Test
public void givenValueBasedPoint_whenCreated_thenReturnsObjects() {
Point p1 = Point.valueOfPoint(1, 2, 3);
Point p2 = Point.valueOfPoint(2, 3, 4);
Assert.assertNotEquals(p1, p2);
}
@Test
public void givenValueBasedPoint_whenCompared_thenReturnEquals() {
Point p1 = Point.valueOfPoint(1, 2, 3);
Point p2 = Point.valueOfPoint(1, 2, 3);
Assert.assertEquals(p1, p2);
}
@Test
public void givenValueBasedPoint_whenOrigin_thenReturnCachedInstance() {
Point p1 = Point.valueOfPoint(0, 0, 0);
Point p2 = Point.valueOfPoint(0, 0, 0);
Point p3 = Point.valueOfPoint(1, 2, 3);
// the following should not be assumed for value-based classes
Assert.assertTrue(p1 == p2);
Assert.assertFalse(p1 == p3);
}
}
+1
View File
@@ -7,3 +7,4 @@
- [Random Number Generators in Java 17](https://www.baeldung.com/java-17-random-number-generators)
- [Sealed Classes and Interfaces in Java](https://www.baeldung.com/java-sealed-classes-interfaces)
- [Migrate From Java 8 to Java 17](https://www.baeldung.com/java-migrate-8-to-17)
- [Format Multiple or Conditions in an If Statement in Java](https://www.baeldung.com/java-multiple-or-conditions-if-statement)
@@ -0,0 +1,126 @@
package com.baeldung.multipleorwithif;
import static java.time.Month.DECEMBER;
import static java.time.Month.NOVEMBER;
import static java.time.Month.OCTOBER;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.in;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.Month;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.function.Predicate;
import org.junit.jupiter.api.Test;
class MultipleOrWithIfUnitTest {
private final Random rand = new Random();
final Set<Month> months = Set.of(OCTOBER, NOVEMBER, DECEMBER);
@Test
public void givenIfStatement_whenMultipleOrOperator_thenAssert() {
assertTrue(multipleOrOperatorIf(monthIn()));
assertFalse(multipleOrOperatorIf(monthNotIn()));
}
boolean multipleOrOperatorIf(Month month) {
if (month == OCTOBER || month == NOVEMBER || month == DECEMBER) {
return true;
}
return false;
}
@Test
public void givenSwitch_whenMultipleCase_thenBreakAndAssert() {
assertTrue(switchMonth(monthIn()));
assertFalse(switchMonth(monthNotIn()));
}
boolean switchMonth(Month month) {
return switch (month) {
case OCTOBER, NOVEMBER, DECEMBER -> true;
default -> false;
};
}
@Test
public void givenAllowedValuesList_whenContains_thenAssert() {
assertTrue(contains(monthIn()));
assertFalse(contains(monthNotIn()));
}
@Test
public void givenPredicates_whenTestMultipleOr_thenAssert() {
assertTrue(predicateWithIf(monthIn()));
assertFalse(predicateWithIf(monthNotIn()));
}
@Test
public void givenInputList_whenFilterWithPredicate_thenAssert() {
List<Month> list = List.of(monthIn(), monthIn(), monthNotIn());
list.stream()
.filter(this::predicateWithIf)
.forEach(m -> assertThat(m, is(in(months))));
}
Predicate<Month> orPredicate() {
Predicate<Month> predicate = x -> x == OCTOBER;
Predicate<Month> predicate1 = x -> x == NOVEMBER;
Predicate<Month> predicate2 = x -> x == DECEMBER;
return predicate.or(predicate1)
.or(predicate2);
}
boolean predicateWithIf(Month month) {
if (orPredicate().test(month)) {
return true;
}
return false;
}
@Test
public void givenContainsInSetPredicate_whenTestPredicate_thenAssert() {
Predicate<Month> collectionPredicate = this::contains;
assertTrue(collectionPredicate.test(monthIn()));
assertFalse(collectionPredicate.test(monthNotIn()));
}
@Test
public void givenInputList_whenFilterWithContains_thenAssert() {
List<Month> monthList = List.of(monthIn(), monthIn(), monthNotIn());
monthList.stream()
.filter(this::contains)
.forEach(m -> assertThat(m, is(in(months))));
}
private boolean contains(Month month) {
if (months.contains(month)) {
return true;
}
return false;
}
private Month monthIn() {
return Month.of(rand.ints(10, 13)
.findFirst()
.orElse(10));
}
private Month monthNotIn() {
return Month.of(rand.ints(1, 10)
.findFirst()
.orElse(1));
}
}
@@ -0,0 +1,89 @@
package com.baeldung.recordproperties;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.lang.reflect.Field;
import java.lang.reflect.RecordComponent;
import java.util.ArrayList;
import org.junit.jupiter.api.Test;
record Player(String name, int age, Long score) {
}
public class ReadRecordPropertiesByReflectionUnitTest {
private static final Player ERIC = new Player("Eric", 28, 4242L);
@Test
void whenUsingRecordComponent_thenGetExpectedResult() {
var fields = new ArrayList<Field>();
RecordComponent[] components = Player.class.getRecordComponents();
for (var comp : components) {
try {
Field field = ERIC.getClass()
.getDeclaredField(comp.getName());
field.setAccessible(true);
fields.add(field);
} catch (NoSuchFieldException e) {
// for simplicity, error handling is skipped
}
}
assertEquals(3, fields.size());
var nameField = fields.get(0);
var ageField = fields.get(1);
var scoreField = fields.get(2);
try {
assertEquals("name", nameField.getName());
assertEquals(String.class, nameField.getType());
assertEquals("Eric", nameField.get(ERIC));
assertEquals("age", ageField.getName());
assertEquals(int.class, ageField.getType());
assertEquals(28, ageField.get(ERIC));
assertEquals("score", scoreField.getName());
assertEquals(Long.class, scoreField.getType());
assertEquals(4242L, scoreField.get(ERIC));
} catch (IllegalAccessException exception) {
// for simplicity, error handling is skipped
}
}
@Test
void whenUsingClassGetDeclaredField_thenGetExpectedResult() {
// record has no public fields
assertEquals(0, Player.class.getFields().length);
var fields = new ArrayList<Field>();
for (var field : Player.class.getDeclaredFields()) {
field.setAccessible(true);
fields.add(field);
}
assertEquals(3, fields.size());
var nameField = fields.get(0);
var ageField = fields.get(1);
var scoreField = fields.get(2);
try {
assertEquals("name", nameField.getName());
assertEquals(String.class, nameField.getType());
assertEquals("Eric", nameField.get(ERIC));
assertEquals("age", ageField.getName());
assertEquals(int.class, ageField.getType());
assertEquals(28, ageField.get(ERIC));
assertEquals("score", scoreField.getName());
assertEquals(Long.class, scoreField.getType());
assertEquals(4242L, scoreField.get(ERIC));
} catch (IllegalAccessException ex) {
// for simplicity, error handling is skipped
}
}
}
+55
View File
@@ -0,0 +1,55 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-18</artifactId>
<name>core-java-18</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<release>${maven.compiler.release}</release>
<compilerArgs>--enable-preview</compilerArgs>
<source>${maven.compiler.source.version}</source>
<target>${maven.compiler.target.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.plugin.version}</version>
<configuration>
<forkCount>1</forkCount>
</configuration>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-api</artifactId>
<version>${surefire.plugin.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source.version>18</maven.compiler.source.version>
<maven.compiler.target.version>18</maven.compiler.target.version>
<maven.compiler.release>18</maven.compiler.release>
<surefire.plugin.version>3.0.0-M5</surefire.plugin.version>
</properties>
</project>
@@ -0,0 +1,27 @@
package com.baeldung.finalization_closeable_cleaner;
import java.io.FileInputStream;
import java.io.IOException;
public class FinalizationExamples {
FileInputStream fis = null;
public void readFileOperationWithFinalization() throws IOException {
try {
fis = new FileInputStream("input.txt");
// perform operation on the file
System.out.println(fis.readAllBytes().length);
} finally {
if (fis != null)
fis.close();
}
}
public void readFileOperationWithTryWith() throws IOException {
try (FileInputStream fis = new FileInputStream("input.txt")) {
// perform operations
System.out.println(fis.readAllBytes().length);
}
}
}
@@ -0,0 +1,48 @@
package com.baeldung.finalization_closeable_cleaner;
import java.lang.ref.Cleaner;
public class MyCleanerResourceClass implements AutoCloseable {
private static Resource resource;
private static final Cleaner cleaner = Cleaner.create();
private final Cleaner.Cleanable cleanable;
public MyCleanerResourceClass() {
resource = new Resource();
this.cleanable = cleaner.register(this, new CleaningState());
}
public void useResource() {
// using the resource here
resource.use();
}
@Override
public void close() {
// perform actions to close all underlying resources
this.cleanable.clean();
}
static class CleaningState implements Runnable {
CleaningState() {
// constructor
}
@Override
public void run() {
// some cleanup action
System.out.println("Cleanup done");
}
}
static class Resource {
void use() {
System.out.println("Using the resource");
}
void close() {
System.out.println("Cleanup done");
}
}
}
@@ -0,0 +1,25 @@
package com.baeldung.finalization_closeable_cleaner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class MyCloseableResourceClass implements AutoCloseable {
private final FileInputStream fis;
public MyCloseableResourceClass() throws FileNotFoundException {
this.fis = new FileInputStream("src/main/resources/file.txt");
}
public int getByteLength() throws IOException {
System.out.println("Some operation");
return this.fis.readAllBytes().length;
}
@Override
public void close() throws IOException {
System.out.println("Finalized object");
this.fis.close();
}
}
@@ -0,0 +1,24 @@
package com.baeldung.finalization_closeable_cleaner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class MyFinalizableResourceClass {
private FileInputStream fis;
public MyFinalizableResourceClass() throws FileNotFoundException {
this.fis = new FileInputStream("src/main/resources/file.txt");
}
public int getByteLength() throws IOException {
System.out.println("Some operation");
return this.fis.readAllBytes().length;
}
@Override
protected void finalize() throws Throwable {
System.out.println("Finalized object");
this.fis.close();
}
}
@@ -0,0 +1 @@
This is a test file.
@@ -0,0 +1,36 @@
package com.baeldung.finalization_closeable_cleaner;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
public class FinalizationCloseableCleanerUnitTest {
@Test
public void givenMyFinalizationResource_whenUsingFinalize_thenShouldClean() {
assertDoesNotThrow(() -> {
MyFinalizableResourceClass mfr = new MyFinalizableResourceClass();
mfr.getByteLength();
});
}
@Test
public void givenMyCleanerResource_whenUsingCleanerAPI_thenShouldClean() {
assertDoesNotThrow(() -> {
try (MyCleanerResourceClass myCleanerResourceClass = new MyCleanerResourceClass()) {
myCleanerResourceClass.useResource();
}
});
}
@Test
public void givenCloseableResource_whenUsingTryWith_thenShouldClose() throws IOException {
int length = 0;
try (MyCloseableResourceClass mcr = new MyCloseableResourceClass()) {
length = mcr.getByteLength();
}
Assert.assertEquals(20, length);
}
}
+5
View File
@@ -0,0 +1,5 @@
## Relevant Articles
- [Sequenced Collections in Java 21](https://www.baeldung.com/java-21-sequenced-collections)
- [String Templates in Java 21](https://www.baeldung.com/java-21-string-templates)
- [Unnamed Classes and Instance Main Methods in Java 21](https://www.baeldung.com/java-21-unnamed-class-instance-main)
- [Unnamed Patterns and Variables in Java 21](https://www.baeldung.com/java-unnamed-patterns-variables)
+47
View File
@@ -0,0 +1,47 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-21</artifactId>
<name>core-java-21</name>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>21</source>
<target>21</target>
<!-- Needed due to a bug with JDK 21, described here: https://issues.apache.org/jira/browse/MCOMPILER-546?page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel&focusedCommentId=17767513 -->
<debug>false</debug>
<compilerArgs>
<arg>--enable-preview</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>--enable-preview</argLine>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source.version>21</maven.compiler.source.version>
<maven.compiler.target.version>21</maven.compiler.target.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
@@ -0,0 +1,15 @@
package com.baeldung.sequenced.collections;
/*
interface SequencedCollection<E> extends Collection<E> {
// new method
SequencedCollection<E> reversed();
// methods promoted from Deque
void addFirst(E);
void addLast(E);
E getFirst();
E getLast();
E removeFirst();
E removeLast();
}
*/
@@ -0,0 +1,18 @@
package com.baeldung.sequenced.collections;
/*
interface SequencedMap<K,V> extends Map<K,V> {
// new methods
SequencedMap<K,V> reversed();
SequencedSet<K> sequencedKeySet();
SequencedCollection<V> sequencedValues();
SequencedSet<Entry<K,V>> sequencedEntrySet();
V putFirst(K, V);
V putLast(K, V);
// methods promoted from NavigableMap
Entry<K, V> firstEntry();
Entry<K, V> lastEntry();
Entry<K, V> pollFirstEntry();
Entry<K, V> pollLastEntry();
}
*/
@@ -0,0 +1,7 @@
package com.baeldung.sequenced.collections;
/*
interface SequencedSet<E> extends Set<E>, SequencedCollection<E> {
SequencedSet<E> reversed(); // covariant override
}
*/
@@ -0,0 +1,37 @@
package com.baeldung.stringtemplates;
import java.text.MessageFormat;
public class StringCompositionTechniques {
String composeUsingPlus(String feelsLike, String temperature, String unit) {
return "Today's weather is " + feelsLike + ", with a temperature of " + temperature + " degrees " + unit;
}
String composeUsingStringBuffer(String feelsLike, String temperature, String unit) {
return new StringBuffer().append("Today's weather is ")
.append(feelsLike)
.append(", with a temperature of ")
.append(temperature)
.append(" degrees ")
.append(unit)
.toString();
}
String composeUsingStringBuilder(String feelsLike, String temperature, String unit) {
return new StringBuilder().append("Today's weather is ")
.append(feelsLike)
.append(", with a temperature of ")
.append(temperature)
.append(" degrees ")
.append(unit)
.toString();
}
String composeUsingFormatters(String feelsLike, String temperature, String unit) {
return String.format("Today's weather is %s, with a temperature of %s degrees %s", feelsLike, temperature, unit);
}
String composeUsingMessageFormatter(String feelsLike, String temperature, String unit) {
return MessageFormat.format("Today''s weather is {0}, with a temperature of {1} degrees {2}", feelsLike, temperature, unit);
}
}
@@ -0,0 +1,56 @@
package com.baeldung.stringtemplates;
import static java.lang.StringTemplate.RAW;
import static java.util.FormatProcessor.FMT;
public class StringTemplateExamples {
String interpolationUsingSTRProcessor(String feelsLike, String temperature, String unit) {
return STR
. "Today's weather is \{ feelsLike }, with a temperature of \{ temperature } degrees \{ unit }" ;
}
String interpolationOfJSONBlock(String feelsLike, String temperature, String unit) {
return STR
. """
{
"feelsLike": "\{ feelsLike }",
"temperature": "\{ temperature }",
"unit": "\{ unit }"
}
""" ;
}
String interpolationWithExpressions() {
return STR
. "Today's weather is \{ getFeelsLike() }, with a temperature of \{ getTemperature() } degrees \{ getUnit() }" ;
}
String interpolationWithTemplates() {
StringTemplate str = RAW
. "Today's weather is \{ getFeelsLike() }, with a temperature of \{ getTemperature() } degrees \{ getUnit() }" ;
return STR.process(str);
}
String interpolationOfJSONBlockWithFMT(String feelsLike, float temperature, String unit) {
return FMT
. """
{
"feelsLike": "%1s\{ feelsLike }",
"temperature": "%2.2f\{ temperature }",
"unit": "%1s\{ unit }"
}
""" ;
}
private String getFeelsLike() {
return "pleasant";
}
private String getTemperature() {
return "25";
}
private String getUnit() {
return "Celsius";
}
}
@@ -0,0 +1,11 @@
package com.baeldung.unnamed.variables;
public record Car<T extends Engine>(String name, String color, T engine) { }
abstract class Engine { }
class GasEngine extends Engine { }
class ElectricEngine extends Engine { }
class HybridEngine extends Engine { }
@@ -0,0 +1,50 @@
package com.baeldung.unnamed.variables;
public class UnnamedPatterns {
static String getObjectsColorWithNamedPattern(Object object) {
if (object instanceof Car(String name, String color, Engine engine)) {
return color;
}
return "No color!";
}
static String getObjectsColorWithUnnamedPattern(Object object) {
if (object instanceof Car(_, String color, _)) {
return color;
}
return "No color!";
}
static String getObjectsColorWithSwitchAndNamedPattern(Object object) {
return switch (object) {
case Car(String name, String color, Engine engine) -> color;
default -> "No color!";
};
}
static String getObjectsColorWithSwitchAndUnnamedPattern(Object object) {
return switch (object) {
case Car(_, String color, _) -> color;
default -> "No color!";
};
}
static String getEngineTypeWithNamedPattern(Car<?> car) {
return switch (car) {
case Car(String name, String color, GasEngine engine) -> "gas";
case Car(String name, String color, ElectricEngine engine) -> "electric";
case Car(String name, String color, HybridEngine engine) -> "hybrid";
default -> "none";
};
}
static String getEngineTypeWithUnnamedPattern(Car<?> car) {
return switch (car) {
case Car(_, _, GasEngine _) -> "gas";
case Car(_, _, ElectricEngine _) -> "electric";
case Car(_, _, HybridEngine _) -> "hybrid";
default -> "none";
};
}
}
@@ -0,0 +1,134 @@
package com.baeldung.unnamed.variables;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
class Transaction implements AutoCloseable {
@Override
public void close() {
System.out.println("Closed!");
}
}
public class UnnamedVariables {
static int countCarsOverLimitWithNamedVariable(Collection<Car<?>> cars, int limit) {
var total = 0;
var totalOverLimit = 0;
for (var car : cars) {
total++;
if (total > limit) {
totalOverLimit++;
// side effect
}
}
return totalOverLimit;
}
static int countCarsOverLimitWithUnnamedVariable(Collection<Car<?>> cars, int limit) {
var total = 0;
var totalOverLimit = 0;
for (var _ : cars) {
total++;
if (total > limit) {
totalOverLimit++;
// side effect
}
}
return totalOverLimit;
}
static void sendNotificationToCarsWithNamedVariable(Collection<Car<?>> cars) {
sendOneTimeNotification();
for (int i = 0; i < cars.size(); i++) {
// Notify car
}
}
static void sendNotificationToCarsWithUnnamedVariable(Collection<Car<?>> cars) {
for (int i = 0, _ = sendOneTimeNotification(); i < cars.size(); i++) {
// Notify car
}
}
private static int sendOneTimeNotification() {
System.out.println("Sending one time notification!");
return 1;
}
static Car<?> removeThreeCarsAndReturnFirstRemovedWithNamedVariables(Queue<Car<?>> cars) {
var x = cars.poll();
var y = cars.poll();
var z = cars.poll();
return x;
}
static Car<?> removeThreeCarsAndReturnFirstRemovedWithUnnamedVariables(Queue<Car<?>> cars) {
var car = cars.poll();
var _ = cars.poll();
var _ = cars.poll();
return car;
}
static void handleCarExceptionWithNamedVariables(Car<?> car) {
try {
someOperationThatFails(car);
} catch (IllegalStateException ex) {
System.out.println("Got an illegal state exception for: " + car.name());
} catch (RuntimeException ex) {
System.out.println("Got a runtime exception!");
}
}
static void handleCarExceptionWithUnnamedVariables(Car<?> car) {
try {
someOperationThatFails(car);
} catch (IllegalStateException | NumberFormatException _) {
System.out.println("Got an illegal state exception for: " + car.name());
} catch (RuntimeException _) {
System.out.println("Got a runtime exception!");
}
}
static void obtainTransactionAndUpdateCarWithNamedVariables(Car<?> car) {
try (var transaction = new Transaction()) {
updateCar(car);
}
}
static void obtainTransactionAndUpdateCarWithUnnamedVariables(Car<?> car) {
try (var _ = new Transaction()) {
updateCar(car);
}
}
static void updateCar(Car<?> car) {
// Some update logic
System.out.println("Car updated!");
}
static Map<String, List<Car<?>>> getCarsByFirstLetterWithNamedVariables(List<Car<?>> cars) {
Map<String, List<Car<?>>> carMap = new HashMap<>();
cars.forEach(car ->
carMap.computeIfAbsent(car.name().substring(0, 1), firstLetter -> new ArrayList<>()).add(car)
);
return carMap;
}
static Map<String, List<Car<?>>> getCarsByFirstLetterWithUnnamedVariables(List<Car<?>> cars) {
Map<String, List<Car<?>>> carMap = new HashMap<>();
cars.forEach(car ->
carMap.computeIfAbsent(car.name().substring(0, 1), _ -> new ArrayList<>()).add(car)
);
return carMap;
}
private static void someOperationThatFails(Car<?> car) {
throw new IllegalStateException("Triggered exception for: " + car.name());
}
}
@@ -0,0 +1,3 @@
void main() {
System.out.println("Hello, World!");
}
@@ -0,0 +1,7 @@
package com.baeldung.unnamedclasses;
public class HelloWorldChild extends HelloWorldSuper {
void main() {
System.out.println("Hello, World!");
}
}
@@ -0,0 +1,7 @@
package com.baeldung.unnamedclasses;
public class HelloWorldSuper {
public static void main(String[] args) {
System.out.println("Hello from the superclass");
}
}
@@ -0,0 +1,6 @@
private String getMessage() {
return "Hello, World!";
}
void main() {
System.out.println(getMessage());
}
@@ -0,0 +1,67 @@
package com.baeldung.stringtemplates;
import org.junit.Assert;
import org.junit.Test;
public class StringTemplatesUnitTest {
@Test
public void whenStringConcat_thenReturnComposedString() {
StringCompositionTechniques stringCompositionTechniques = new StringCompositionTechniques();
Assert.assertEquals("Today's weather is pleasant, with a temperature of 25 degrees Celsius", stringCompositionTechniques.composeUsingPlus("pleasant", "25", "Celsius"));
}
@Test
public void whenStringBuffer_thenReturnComposedString() {
StringCompositionTechniques stringCompositionTechniques = new StringCompositionTechniques();
Assert.assertEquals("Today's weather is pleasant, with a temperature of 25 degrees Celsius", stringCompositionTechniques.composeUsingStringBuffer("pleasant", "25", "Celsius"));
}
@Test
public void whenStringBuilder_thenReturnComposedString() {
StringCompositionTechniques stringCompositionTechniques = new StringCompositionTechniques();
Assert.assertEquals("Today's weather is pleasant, with a temperature of 25 degrees Celsius", stringCompositionTechniques.composeUsingStringBuilder("pleasant", "25", "Celsius"));
}
@Test
public void whenStringFormatter_thenReturnComposedFormattedString() {
StringCompositionTechniques stringCompositionTechniques = new StringCompositionTechniques();
Assert.assertEquals("Today's weather is pleasant, with a temperature of 25 degrees Celsius", stringCompositionTechniques.composeUsingFormatters("pleasant", "25", "Celsius"));
}
@Test
public void whenMessageFormatter_thenReturnComposedFormattedString() {
StringCompositionTechniques stringCompositionTechniques = new StringCompositionTechniques();
Assert.assertEquals("Today's weather is pleasant, with a temperature of 25 degrees Celsius", stringCompositionTechniques.composeUsingMessageFormatter("pleasant", "25", "Celsius"));
}
@Test
public void whenUsingStringTemplateSTR_thenReturnInterpolatedString() {
StringTemplateExamples templateExamples = new StringTemplateExamples();
Assert.assertEquals("Today's weather is pleasant, with a temperature of 25 degrees Celsius", templateExamples.interpolationUsingSTRProcessor("pleasant", "25", "Celsius"));
}
@Test
public void whenUsingMultilineStringTemplateSTR_thenReturnInterpolatedString() {
StringTemplateExamples templateExamples = new StringTemplateExamples();
Assert.assertEquals("{\n" + " \"feelsLike\": \"pleasant\",\n" + " \"temperature\": \"25\",\n" + " \"unit\": \"Celsius\"\n" + "}\n", templateExamples.interpolationOfJSONBlock("pleasant", "25", "Celsius"));
}
@Test
public void whenUsingExpressionSTR_thenReturnInterpolatedString() {
StringTemplateExamples templateExamples = new StringTemplateExamples();
Assert.assertEquals("Today's weather is pleasant, with a temperature of 25 degrees Celsius", templateExamples.interpolationWithExpressions());
}
@Test
public void whenUsingExpressionRAW_thenReturnInterpolatedString() {
StringTemplateExamples templateExamples = new StringTemplateExamples();
Assert.assertEquals("Today's weather is pleasant, with a temperature of 25 degrees Celsius", templateExamples.interpolationWithTemplates());
}
@Test
public void whenUsingExpressionFMT_thenReturnInterpolatedString() {
StringTemplateExamples templateExamples = new StringTemplateExamples();
Assert.assertEquals("{\n" + " \"feelsLike\": \"pleasant\",\n" + " \"temperature\": \"25.86\",\n" + " \"unit\": \"Celsius\"\n" + "}\n", templateExamples.interpolationOfJSONBlockWithFMT("pleasant", 25.8636F, "Celsius"));
}
}
@@ -0,0 +1,13 @@
package com.baeldung.unnamed.variables;
import java.util.List;
class CarScenario {
protected final List<Car<?>> cars = List.of(
new Car<>("Mitsubishi", "blue", new GasEngine()),
new Car<>("Toyota", "red", new ElectricEngine()),
new Car<>("Jaguar", "white", new HybridEngine())
);
}
@@ -0,0 +1,44 @@
package com.baeldung.unnamed.variables;
import static com.baeldung.unnamed.variables.UnnamedPatterns.getEngineTypeWithNamedPattern;
import static com.baeldung.unnamed.variables.UnnamedPatterns.getEngineTypeWithUnnamedPattern;
import static com.baeldung.unnamed.variables.UnnamedPatterns.getObjectsColorWithNamedPattern;
import static com.baeldung.unnamed.variables.UnnamedPatterns.getObjectsColorWithSwitchAndNamedPattern;
import static com.baeldung.unnamed.variables.UnnamedPatterns.getObjectsColorWithSwitchAndUnnamedPattern;
import static com.baeldung.unnamed.variables.UnnamedPatterns.getObjectsColorWithUnnamedPattern;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class UnnamedPatternsUnitTest extends CarScenario {
@Test
public void whenExtractingColorWithNamedPatterns_thenReturnBlue() {
assertEquals("blue", getObjectsColorWithNamedPattern(cars.get(0)));
}
@Test
public void whenExtractingColorWithUnnamedPatterns_thenReturnBlue() {
assertEquals("blue", getObjectsColorWithUnnamedPattern(cars.get(0)));
}
@Test
public void whenExtractingColorWithSwitchAndNamedPatterns_thenReturnBlue() {
assertEquals("blue", getObjectsColorWithSwitchAndNamedPattern(cars.get(0)));
}
@Test
public void whenExtractingColorWithSwitchAndUnnamedPatterns_thenReturnBlue() {
assertEquals("blue", getObjectsColorWithSwitchAndUnnamedPattern(cars.get(0)));
}
@Test
public void whenExtractingEngineTypeWithNamedPatterns_thenReturnGas() {
assertEquals("gas", getEngineTypeWithNamedPattern(cars.get(0)));
}
@Test
public void whenExtractingEngineTypeWithUnnamedPatterns_thenReturnGas() {
assertEquals("gas", getEngineTypeWithUnnamedPattern(cars.get(0)));
}
}
@@ -0,0 +1,93 @@
package com.baeldung.unnamed.variables;
import static com.baeldung.unnamed.variables.UnnamedVariables.countCarsOverLimitWithNamedVariable;
import static com.baeldung.unnamed.variables.UnnamedVariables.countCarsOverLimitWithUnnamedVariable;
import static com.baeldung.unnamed.variables.UnnamedVariables.getCarsByFirstLetterWithNamedVariables;
import static com.baeldung.unnamed.variables.UnnamedVariables.getCarsByFirstLetterWithUnnamedVariables;
import static com.baeldung.unnamed.variables.UnnamedVariables.handleCarExceptionWithNamedVariables;
import static com.baeldung.unnamed.variables.UnnamedVariables.handleCarExceptionWithUnnamedVariables;
import static com.baeldung.unnamed.variables.UnnamedVariables.obtainTransactionAndUpdateCarWithNamedVariables;
import static com.baeldung.unnamed.variables.UnnamedVariables.obtainTransactionAndUpdateCarWithUnnamedVariables;
import static com.baeldung.unnamed.variables.UnnamedVariables.removeThreeCarsAndReturnFirstRemovedWithNamedVariables;
import static com.baeldung.unnamed.variables.UnnamedVariables.removeThreeCarsAndReturnFirstRemovedWithUnnamedVariables;
import static com.baeldung.unnamed.variables.UnnamedVariables.sendNotificationToCarsWithNamedVariable;
import static com.baeldung.unnamed.variables.UnnamedVariables.sendNotificationToCarsWithUnnamedVariable;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.LinkedList;
import org.junit.jupiter.api.Test;
public class UnnamedVariablesUnitTest extends CarScenario {
@Test
public void whenCountingCarsOverLimitWithNamedVariables_thenShouldReturnOne() {
assertEquals(1, countCarsOverLimitWithNamedVariable(cars, 2));
}
@Test
public void whenCountingCarsOverLimitWithUnnamedVariables_thenShouldReturnOne() {
assertEquals(1, countCarsOverLimitWithUnnamedVariable(cars, 2));
}
@Test
public void whenNotifyingCarsWithNamedVariables_thenShouldNotFail() {
assertDoesNotThrow(() -> sendNotificationToCarsWithNamedVariable(cars));
}
@Test
public void whenNotifyingCarsWithUnnamedVariables_thenShouldNotFail() {
assertDoesNotThrow(() -> sendNotificationToCarsWithUnnamedVariable(cars));
}
@Test
public void whenPollingCarsWithNamedVariables_thenReturnFirstOneAndEmptyQueue() {
var carQueue = new LinkedList<>(cars);
assertEquals("Mitsubishi", removeThreeCarsAndReturnFirstRemovedWithNamedVariables(carQueue).name());
assertEquals(0, carQueue.size());
}
@Test
public void whenPollingCarsWithUnnamedVariables_thenReturnFirstOneAndEmptyQueue() {
var carQueue = new LinkedList<>(cars);
assertEquals("Mitsubishi", removeThreeCarsAndReturnFirstRemovedWithUnnamedVariables(carQueue).name());
assertEquals(0, carQueue.size());
}
@Test
public void whenHandlingExceptionWithNamedVariables_thenNoExceptionIsThrown() {
assertDoesNotThrow(() -> handleCarExceptionWithNamedVariables(cars.get(0)));
}
@Test
public void whenHandlingExceptionWithUnnamedVariables_thenNoExceptionIsThrown() {
assertDoesNotThrow(() -> handleCarExceptionWithUnnamedVariables(cars.get(0)));
}
@Test
public void whenHandlingTransactionUpdateWithNamedVariables_thenNoExceptionIsThrown() {
assertDoesNotThrow(() -> obtainTransactionAndUpdateCarWithNamedVariables(cars.get(0)));
}
@Test
public void whenHandlingTransactionUpdateWithUnnamedVariables_thenNoExceptionIsThrown() {
assertDoesNotThrow(() -> obtainTransactionAndUpdateCarWithUnnamedVariables(cars.get(0)));
}
@Test
public void whenGettingCarsByFirstLetterWithNamedVariables_thenHaveThreeKeys() {
var carsByLetter = getCarsByFirstLetterWithNamedVariables(cars);
assertEquals(1, carsByLetter.get("M").size());
assertEquals(1, carsByLetter.get("T").size());
assertEquals(1, carsByLetter.get("J").size());
}
@Test
public void whenGettingCarsByFirstLetterWithUnnamedVariables_thenHaveThreeKeys() {
var carsByLetter = getCarsByFirstLetterWithUnnamedVariables(cars);
assertEquals(1, carsByLetter.get("M").size());
assertEquals(1, carsByLetter.get("T").size());
assertEquals(1, carsByLetter.get("J").size());
}
}
@@ -5,4 +5,5 @@
- [Parsing Date Strings with Varying Formats](https://www.baeldung.com/java-parsing-dates-many-formats)
- [How Many Days Are There in a Particular Month of a Given Year?](https://www.baeldung.com/days-particular-month-given-year)
- [Difference Between Instant and LocalDateTime](https://www.baeldung.com/java-instant-vs-localdatetime)
- [Add Minutes to a Time String in Java](https://www.baeldung.com/java-string-time-add-mins)
- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1)
@@ -0,0 +1,37 @@
package com.baeldung.stringtime;
import static org.junit.jupiter.api.Assertions.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.util.Calendar;
import java.util.Date;
import org.junit.jupiter.api.Test;
public class AddMinuteStringTimeUnitTest {
@Test
public void givenTimeStringUsingSimpleDateFormat_whenIncrementedWith10Minutes_thenResultShouldBeCorrect() throws ParseException {
String timeString = "23:45";
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
Date date = timeFormat.parse(timeString);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MINUTE, 10);
String result = timeFormat.format(cal.getTime());
assertEquals("23:55", result);
}
@Test
public void givenTimeStringUsingLocalTime_whenIncrementedWith10Minutes_thenResultShouldBeCorrect() {
String timeString = "23:45";
LocalTime time = LocalTime.parse(timeString);
LocalTime newTime = time.plusMinutes(10);
String result = newTime.toString();
assertEquals("23:55", result);
}
}
@@ -3,9 +3,11 @@ package com.baeldung.dateapi;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
@@ -19,7 +21,7 @@ public class JavaDurationUnitTest {
LocalTime finalTime = initialTime.plus(Duration.ofSeconds(30));
long seconds = Duration.between(initialTime, finalTime)
.getSeconds();
.getSeconds();
assertThat(seconds).isEqualTo(30);
}
@@ -34,6 +36,22 @@ public class JavaDurationUnitTest {
assertThat(seconds).isEqualTo(30);
}
@Test
public void givenADuration_whenCallingisZeroAndisNegative_thenGetExpectedResult() {
LocalDateTime start = LocalDateTime.parse("2020-01-01T08:00:00");
LocalDateTime end = LocalDateTime.parse("2020-01-01T12:00:00");
assertFalse(Duration.between(start, end)
.isNegative());
assertTrue(Duration.between(end, start)
.isNegative());
LocalDateTime theTime = LocalDateTime.parse("2023-09-09T08:00:00");
assertTrue(Duration.between(theTime, theTime)
.isZero());
assertFalse(Duration.between(theTime, theTime)
.isNegative());
}
@Test
public void test2() {
Instant start = Instant.parse("2017-10-03T10:15:30.00Z");
@@ -53,17 +71,17 @@ public class JavaDurationUnitTest {
assertEquals(1, fromMinutes.toHours());
assertEquals(120, duration.plusSeconds(60)
.getSeconds());
.getSeconds());
assertEquals(30, duration.minusSeconds(30)
.getSeconds());
.getSeconds());
assertEquals(120, duration.plus(60, ChronoUnit.SECONDS)
.getSeconds());
.getSeconds());
assertEquals(30, duration.minus(30, ChronoUnit.SECONDS)
.getSeconds());
.getSeconds());
Duration fromChar1 = Duration.parse("P1DT1H10M10.5S");
Duration fromChar2 = Duration.parse("PT10M");
}
}
}
@@ -10,7 +10,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
<relativePath>../../pom.xml</relativePath>
</parent>
<dependencies>
@@ -4,9 +4,9 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung</groupId>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-9-jigsaw</artifactId>
<version>0.2-SNAPSHOT</version>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>library-core</artifactId>
+3 -4
View File
@@ -11,10 +11,9 @@
</modules>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<build>
@@ -152,7 +152,6 @@
<awaitility.version>4.0.2</awaitility.version>
<maven.compiler.source>1.9</maven.compiler.source>
<maven.compiler.target>1.9</maven.compiler.target>
<maven-jar-plugin.version>3.2.0</maven-jar-plugin.version>
</properties>
</project>
@@ -4,3 +4,4 @@ This module contains articles about Java 9 streams
### Relevant Articles:
- [How to Break from Java Stream forEach](https://www.baeldung.com/java-break-stream-foreach)
- [Creating Stream of Regex Matches](https://www.baeldung.com/java-stream-regex-matches)
@@ -0,0 +1,16 @@
package com.baeldung.streams.regexmatches;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
public class StreamFromRegexUtil {
public static Stream<String> getStream(String input, String regex) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
return matcher.results().map(MatchResult::group);
}
}
@@ -0,0 +1,27 @@
package com.baeldung.streams.regexmatches;
import org.junit.Test;
import java.util.List;
import java.util.stream.Collectors;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
public class StreamFromRegexUnitTest {
@Test
public void whenInputStringIncludeLettersAndNumbersAndRegex_ThenReturnStreamOfNumbers() {
List<String> result = StreamFromRegexUtil.getStream("There are 3 apples and 2 bananas on the table.", "\\d+")
.collect(Collectors.toList());
assertEquals(asList("3", "2"), result);
}
@Test
public void whenInputStringsAndRegex_ThenReturnStreamOfJavaWords() {
List<String> result = StreamFromRegexUtil.getStream("sample sentence with some words Java Java", "\\bJava\\b")
.collect(Collectors.toList());
assertEquals(asList("Java", "Java"), result);
}
}
+1
View File
@@ -12,3 +12,4 @@ This module contains articles about Java 9 core features
- [Private Methods in Java Interfaces](https://www.baeldung.com/java-interface-private-methods)
- [Java Scanner useDelimiter with Examples](https://www.baeldung.com/java-scanner-usedelimiter)
- [Is There a Destructor in Java?](https://www.baeldung.com/java-destructor)
- [Java 9 Migration Issues and Resolutions](https://www.baeldung.com/java-9-migration-issue)
+9
View File
@@ -46,6 +46,11 @@
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>${javax.xml.bind.version}</version>
</dependency>
</dependencies>
<build>
@@ -58,6 +63,9 @@
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<compilerArgs>
<arg>--add-exports=java.base/com.sun.crypto.provider=ALL-UNNAMED</arg>
</compilerArgs>
</configuration>
</plugin>
</plugins>
@@ -74,6 +82,7 @@
<awaitility.version>1.7.0</awaitility.version>
<maven.compiler.source>1.9</maven.compiler.source>
<maven.compiler.target>1.9</maven.compiler.target>
<javax.xml.bind.version>2.4.0-b180725.0427</javax.xml.bind.version>
</properties>
</project>
@@ -1,15 +1,16 @@
package com.baeldung.prejpms;
package com.baeldung.java9.prejpms;
import java.io.StringWriter;
import java.lang.StackWalker.Option;
import java.lang.StackWalker.StackFrame;
import com.sun.crypto.provider.SunJCE;
import java.util.Base64;
import java.util.concurrent.atomic.AtomicInteger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import com.sun.crypto.provider.SunJCE;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -1,4 +1,4 @@
package com.baeldung.prejpms;
package com.baeldung.java9.prejpms;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
@@ -8,3 +8,6 @@ This module contains articles about arrays conversion in Java
- [Convert a Byte Array to a Numeric Representation in Java](https://www.baeldung.com/java-byte-array-to-number)
- [Converting a String Array Into an int Array in Java](https://www.baeldung.com/java-convert-string-array-to-int-array)
- [Convert Java Array to Iterable](https://www.baeldung.com/java-array-convert-to-iterable)
- [Converting an int[] to HashSet in Java](https://www.baeldung.com/java-converting-int-array-to-hashset)
- [Convert an ArrayList of String to a String Array in Java](https://www.baeldung.com/java-convert-string-arraylist-array)
- [Convert Char Array to Int Array in Java](https://www.baeldung.com/java-convert-char-int-array)
@@ -20,5 +20,4 @@
<version>${commons-lang3.version}</version>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,67 @@
package com.baeldung.array.conversions;
import java.util.Arrays;
public class CharArrayToIntArrayUtils {
static int[] usingGetNumericValueMethod(char[] chars) {
if (chars == null) {
return null;
}
int[] ints = new int[chars.length];
for (int i = 0; i < chars.length; i++) {
ints[i] = Character.getNumericValue(chars[i]);
}
return ints;
}
static int[] usingDigitMethod(char[] chars) {
if (chars == null) {
return null;
}
int[] ints = new int[chars.length];
for (int i = 0; i < chars.length; i++) {
ints[i] = Character.digit(chars[i], 10);
}
return ints;
}
static int[] usingStreamApiMethod(char[] chars) {
if (chars == null) {
return null;
}
return new String(chars).chars()
.map(c -> c - 48)
.toArray();
}
static int[] usingParseIntMethod(char[] chars) {
if (chars == null) {
return null;
}
int[] ints = new int[chars.length];
for (int i = 0; i < chars.length; i++) {
ints[i] = Integer.parseInt(String.valueOf(chars[i]));
}
return ints;
}
static int[] usingArraysSetAllMethod(char[] chars) {
if (chars == null) {
return null;
}
int[] ints = new int[chars.length];
Arrays.setAll(ints, i -> Character.getNumericValue(chars[i]));
return ints;
}
}
@@ -0,0 +1,54 @@
package com.baeldung.array.conversions;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.jupiter.api.Test;
class CharArrayToIntArrayUtilsUnitTest {
@Test
void givenCharArray_whenUsingGetNumericValueMethod_shouldGetIntArray() {
int[] expected = { 2, 3, 4, 5 };
char[] chars = { '2', '3', '4', '5' };
int[] result = CharArrayToIntArrayUtils.usingGetNumericValueMethod(chars);
assertArrayEquals(expected, result);
}
@Test
void givenCharArray_whenUsingDigitMethod_shouldGetIntArray() {
int[] expected = { 1, 2, 3, 6 };
char[] chars = { '1', '2', '3', '6' };
int[] result = CharArrayToIntArrayUtils.usingDigitMethod(chars);
assertArrayEquals(expected, result);
}
@Test
void givenCharArray_whenUsingStreamApi_shouldGetIntArray() {
int[] expected = { 9, 8, 7, 6 };
char[] chars = { '9', '8', '7', '6' };
int[] result = CharArrayToIntArrayUtils.usingStreamApiMethod(chars);
assertArrayEquals(expected, result);
}
@Test
void givenCharArray_whenUsingParseIntMethod_shouldGetIntArray() {
int[] expected = { 9, 8, 7, 6 };
char[] chars = { '9', '8', '7', '6' };
int[] result = CharArrayToIntArrayUtils.usingParseIntMethod(chars);
assertArrayEquals(expected, result);
}
@Test
void givenCharArray_whenUsingArraysSetAllMethod_shouldGetIntArray() {
int[] expected = { 4, 9, 2, 3 };
char[] chars = { '4', '9', '2', '3' };
int[] result = CharArrayToIntArrayUtils.usingArraysSetAllMethod(chars);
assertArrayEquals(expected, result);
}
}
@@ -9,3 +9,4 @@ This module contains complete guides about arrays in Java
- [Guide to ArrayStoreException](https://www.baeldung.com/java-arraystoreexception)
- [Creating a Generic Array in Java](https://www.baeldung.com/java-generic-array)
- [Maximum Size of Java Arrays](https://www.baeldung.com/java-arrays-max-size)
- [Merge Two Arrays and Remove Duplicates in Java](https://www.baeldung.com/java-merge-two-arrays-delete-duplicates)
@@ -0,0 +1,96 @@
package com.baeldung.mergeandremoveduplicate;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Stream;
public class MergeArraysAndRemoveDuplicate {
public static int[] removeDuplicateOnSortedArray(int[] arr) {
// Initialize a new array to store unique elements
int[] uniqueArray = new int[arr.length];
uniqueArray[0] = arr[0];
int uniqueCount = 1;
// Iterate through the sorted array to remove duplicates
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[i - 1]) {
uniqueArray[uniqueCount] = arr[i];
uniqueCount++;
}
}
int[] truncatedArray = new int[uniqueCount];
System.arraycopy(uniqueArray, 0, truncatedArray, 0, uniqueCount);
return truncatedArray;
}
public static int[] mergeAndRemoveDuplicatesUsingStream(int[] arr1, int[] arr2) {
Stream<Integer> s1 = Arrays.stream(arr1).boxed();
Stream<Integer> s2 = Arrays.stream(arr2).boxed();
return Stream.concat(s1, s2)
.distinct()
.mapToInt(Integer::intValue)
.toArray();
}
public static int[] mergeAndRemoveDuplicatesUsingSet(int[] arr1, int[] arr2) {
int[] mergedArr = mergeArrays(arr1, arr2);
Set<Integer> uniqueInts = new HashSet<>();
for (int el : mergedArr) {
uniqueInts.add(el);
}
return getArrayFromSet(uniqueInts);
}
private static int[] getArrayFromSet(Set<Integer> set) {
int[] mergedArrWithoutDuplicated = new int[set.size()];
int i = 0;
for (Integer el: set) {
mergedArrWithoutDuplicated[i] = el;
i++;
}
return mergedArrWithoutDuplicated;
}
public static int[] mergeAndRemoveDuplicates(int[] arr1, int[] arr2) {
return removeDuplicate(mergeArrays(arr1, arr2));
}
public static int[] mergeAndRemoveDuplicatesOnSortedArray(int[] arr1, int[] arr2) {
return removeDuplicateOnSortedArray(mergeArrays(arr1, arr2));
}
private static int[] mergeArrays(int[] arr1, int[] arr2) {
int[] mergedArrays = new int[arr1.length + arr2.length];
System.arraycopy(arr1, 0, mergedArrays, 0, arr1.length);
System.arraycopy(arr2, 0, mergedArrays, arr1.length, arr2.length);
return mergedArrays;
}
private static int[] removeDuplicate(int[] arr) {
int[] withoutDuplicates = new int[arr.length];
int i = 0;
for(int element : arr) {
if(!isElementPresent(withoutDuplicates, element)) {
withoutDuplicates[i] = element;
i++;
}
}
int[] truncatedArray = new int[i];
System.arraycopy(withoutDuplicates, 0, truncatedArray, 0, i);
return truncatedArray;
}
private static boolean isElementPresent(int[] arr, int element) {
for(int el : arr) {
if(el == element) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,74 @@
package com.baeldung.mergeandremoveduplicate;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
public class MergeArraysAndRemoveDuplicateUnitTest {
private final Logger logger = LoggerFactory.getLogger(MergeArraysAndRemoveDuplicateUnitTest.class);
private static String getCommaDelimited(int[] arr) {
return Arrays.stream(arr)
.mapToObj(Integer::toString)
.collect(Collectors.joining(", "));
}
@Test
public void givenNoLibraryAndUnSortedArrays_whenArr1andArr2_thenMergeAndRemoveDuplicates() {
int[] arr1 = {3, 2, 1, 4, 5, 6, 8, 7, 9};
int[] arr2 = {8, 9, 10, 11, 12, 13, 15, 14, 15, 14, 16, 17};
int[] expectedArr = {3, 2, 1, 4, 5, 6, 8, 7, 9, 10, 11, 12, 13, 15, 14, 16, 17};
int[] mergedArr = MergeArraysAndRemoveDuplicate.mergeAndRemoveDuplicates(arr1, arr2);
//merged array maintains the order of the elements in the arrays
assertArrayEquals(expectedArr, mergedArr);
logger.info(getCommaDelimited(mergedArr));
}
@Test
public void givenNoLibraryAndSortedArrays_whenArr1andArr2_thenMergeAndRemoveDuplicates() {
int[] arr1 = {1, 2, 3, 4, 5, 5, 6, 7, 7, 8};
int[] arr2 = {8, 9, 10, 11, 12, 13, 14, 15, 15, 16, 17};
int[] expectedArr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17};
int[] mergedArr = MergeArraysAndRemoveDuplicate.mergeAndRemoveDuplicatesOnSortedArray(arr1, arr2);
assertArrayEquals(expectedArr, mergedArr);
logger.info(getCommaDelimited(mergedArr));
}
@Test
public void givenSet_whenArr1andArr2_thenMergeAndRemoveDuplicates() {
int[] arr1 = {3, 2, 1, 4, 5, 6, 8, 7, 9};
int[] arr2 = {8, 9, 10, 11, 12, 13, 15, 14, 15, 14, 16, 17};
int[] expectedArr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17};
int[] mergedArr = MergeArraysAndRemoveDuplicate.mergeAndRemoveDuplicatesUsingSet(arr1, arr2);
assertArrayEquals(expectedArr, mergedArr);
logger.info(getCommaDelimited(mergedArr));
}
@Test
public void givenStream_whenArr1andArr2_thenMergeAndRemoveDuplicates() {
int[] arr1 = {3, 2, 1, 4, 5, 6, 8, 7, 9};
int[] arr2 = {8, 9, 10, 11, 12, 13, 15, 14, 15, 14, 16, 17};
int[] expectedArr = {3, 2, 1, 4, 5, 6, 8, 7, 9, 10, 11, 12, 13, 15, 14, 16, 17};
int[] mergedArr = MergeArraysAndRemoveDuplicate.mergeAndRemoveDuplicatesUsingStream(arr1, arr2);
assertArrayEquals(expectedArr, mergedArr);
logger.info(getCommaDelimited(mergedArr));
}
}
@@ -0,0 +1,2 @@
## Relevant Articles
- [Find the Middle Element of an Array in Java](https://www.baeldung.com/java-array-middle-item)
@@ -0,0 +1,46 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-arrays-operations-advanced-2</artifactId>
<name>core-java-arrays-operations-advanced-2</name>
<packaging>jar</packaging>
<parent>
<artifactId>core-java-modules</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,65 @@
package com.baeldung.arraymiddle;
import java.util.Arrays;
import org.apache.commons.lang3.ObjectUtils;
public class MiddleOfArray {
int[] middleOfArray(int[] array) {
if (ObjectUtils.isEmpty(array) || array.length < 3)
return array;
int n = array.length;
int mid = n / 2;
if (n % 2 == 0) {
int mid2 = mid - 1;
return new int[] { array[mid2], array[mid] };
} else {
return new int[] { array[mid] };
}
}
int[] middleOfArrayWithStartEndNaive(int[] array, int start, int end) {
int mid = (start + end) / 2;
int n = end - start;
if (n % 2 == 0) {
int mid2 = mid - 1;
return new int[] { array[mid2], array[mid] };
} else {
return new int[] { array[mid] };
}
}
int[] middleOfArrayWithStartEnd(int[] array, int start, int end) {
int mid = start + (end - start) / 2;
int n = end - start;
if (n % 2 == 0) {
int mid2 = mid - 1;
return new int[] { array[mid2], array[mid] };
} else {
return new int[] { array[mid] };
}
}
int[] middleOfArrayWithStartEndBitwise(int[] array, int start, int end) {
int mid = (start + end) >>> 1;
int n = end - start;
if (n % 2 == 0) {
int mid2 = mid - 1;
return new int[] { array[mid2], array[mid] };
} else {
return new int[] { array[mid] };
}
}
int medianOfArray(int[] array, int start, int end) {
Arrays.sort(array); // for safety. This can be ignored
int mid = (start + end) >>> 1;
int n = end - start;
if (n % 2 == 0) {
int mid2 = mid - 1;
return (array[mid2] + array[mid]) / 2;
} else {
return array[mid];
}
}
}
@@ -0,0 +1,89 @@
package com.baeldung.arraymiddle;
import org.junit.Assert;
import org.junit.Test;
public class MiddleOfArrayUnitTest {
@Test
public void givenArrayOfEvenLength_whenMiddleOfArray_thenReturn2Values() {
int[] array = new int[100];
for (int i = 0; i < array.length; i++) {
array[i] = i + 1;
}
int[] expectedMidArray = { 50, 51 };
MiddleOfArray middleOfArray = new MiddleOfArray();
Assert.assertArrayEquals(expectedMidArray, middleOfArray.middleOfArray(array));
}
@Test
public void givenArrayOfEdgeCaseLength_whenMiddleOfArray_thenReturn2Values() {
int[] array = new int[0];
int[] expectedMidArray = new int[0];
MiddleOfArray middleOfArray = new MiddleOfArray();
Assert.assertArrayEquals(expectedMidArray, middleOfArray.middleOfArray(array));
array = new int[] { 1, 2 };
expectedMidArray = new int[] { 1, 2 };
Assert.assertArrayEquals(expectedMidArray, middleOfArray.middleOfArray(array));
}
@Test
public void givenArrayOfOddLength_whenMiddleOfArray_thenReturnMid() {
int[] array = new int[99];
for (int i = 0; i < array.length; i++) {
array[i] = i + 1;
}
int[] expectedMidArray = { 50 };
MiddleOfArray middleOfArray = new MiddleOfArray();
Assert.assertArrayEquals(expectedMidArray, middleOfArray.middleOfArray(array));
}
@Test
public void givenArrayWithStartAndEnd_whenMiddleOfArray_thenReturnMid() {
int[] array = new int[100];
for (int i = 0; i < array.length; i++) {
array[i] = i + 1;
}
int[] expectedMidArray = { 58 };
MiddleOfArray middleOfArray = new MiddleOfArray();
Assert.assertArrayEquals(expectedMidArray, middleOfArray.middleOfArrayWithStartEndNaive(array, 55, 60));
expectedMidArray = new int[] { 58, 59 };
Assert.assertArrayEquals(expectedMidArray, middleOfArray.middleOfArrayWithStartEndNaive(array, 56, 60));
}
@Test
public void givenArrayWithStartAndEndOptimized_whenMiddleOfArray_thenReturnMid() {
int[] array = new int[100];
for (int i = 0; i < array.length; i++) {
array[i] = i + 1;
}
int[] expectedMidArray = { 78 };
MiddleOfArray middleOfArray = new MiddleOfArray();
Assert.assertArrayEquals(expectedMidArray, middleOfArray.middleOfArrayWithStartEnd(array, 55, 100));
}
@Test
public void givenArrayWithStartAndEndBitwise_whenMiddleOfArray_thenReturnMid() {
int[] array = new int[100];
for (int i = 0; i < array.length; i++) {
array[i] = i + 1;
}
int[] expectedMidArray = { 78 };
MiddleOfArray middleOfArray = new MiddleOfArray();
Assert.assertArrayEquals(expectedMidArray, middleOfArray.middleOfArrayWithStartEndBitwise(array, 55, 100));
}
@Test
public void givenArrayWithStartAndEnd_whenMedianOfArray_thenReturnMid() {
int[] array = new int[100];
for (int i = 0; i < array.length; i++) {
array[i] = i + 1;
}
int expectMedian = 50;
MiddleOfArray middleOfArray = new MiddleOfArray();
Assert.assertEquals(expectMedian, middleOfArray.medianOfArray(array, 0, 100));
}
}
@@ -13,3 +13,4 @@ This module contains articles about advanced operations on arrays in Java. They
- [Performance of System.arraycopy() vs. Arrays.copyOf()](https://www.baeldung.com/java-system-arraycopy-arrays-copyof-performance)
- [Slicing Arrays in Java](https://www.baeldung.com/java-slicing-arrays)
- [Combining Two or More Byte Arrays](https://www.baeldung.com/java-concatenate-byte-arrays)
- [Calculating the Sum of Two Arrays in Java](https://www.baeldung.com/java-sum-arrays-element-wise)
@@ -0,0 +1,14 @@
package com.baeldung.arraysums;
public class SumArraysUsingForEach {
public static int[] sumOfTwoArrays(int[] arr1, int[] arr2) {
int[] arr3 = new int[arr1.length];
int counter = 0;
for (int num1 : arr1) {
arr3[counter] = num1 + arr2[counter];
counter++;
}
return arr3;
}
}
@@ -0,0 +1,12 @@
package com.baeldung.arraysums;
public class SumArraysUsingForLoop {
public static int[] sumOfTwoArrays(int[] arr1, int[] arr2) {
int[] arr3 = new int[arr1.length];
for (int i = 0; i < arr1.length; i++) {
arr3[i] = arr1[i] + arr2[i];
}
return arr3;
}
}
@@ -0,0 +1,14 @@
package com.baeldung.arraysums;
import java.util.Arrays;
import java.util.stream.IntStream;
public class SumArraysUsingStreams {
public static int[] sumOfTwoArrays(int[] arr1, int[] arr2) {
IntStream range = IntStream.range(0, Math.min(arr1.length, arr2.length));
IntStream stream3 = range.map(i -> arr1[i] + arr2[i]);
int[] arr3 = stream3.toArray();
return arr3;
}
}
@@ -0,0 +1,16 @@
package com.baeldung.arraysums;
import com.baeldung.arraysums.SumArraysUsingForEach;
import org.junit.Test;
import static org.junit.Assert.*;
public class SumArraysUsingForEachUnitTest {
@Test
public void sumOfTwoArraysUsingForEach_GivenTwoEqualSizedIntArrays_ReturnsCorrectSumArray() {
int[] arr1 = { 4, 5, 1, 6, 4, 15 };
int[] arr2 = { 3, 5, 6, 1, 9, 6 };
int[] expected = { 7, 10, 7, 7, 13, 21 };
assertArrayEquals(expected, SumArraysUsingForEach.sumOfTwoArrays(arr1, arr2));
}
}
@@ -0,0 +1,16 @@
package com.baeldung.arraysums;
import com.baeldung.arraysums.SumArraysUsingForLoop;
import org.junit.Test;
import static org.junit.Assert.*;
public class SumArraysUsingForLoopUnitTest {
@Test
public void sumOfTwoArrays_GivenTwoEqualSizedIntArrays_ReturnsCorrectSumArray() {
int[] arr1 = {4, 5, 1, 6, 4, 15};
int[] arr2 = {3, 5, 6, 1, 9, 6};
int[] expected = {7, 10, 7, 7, 13, 21};
assertArrayEquals(expected, SumArraysUsingForLoop.sumOfTwoArrays(arr1, arr2));
}
}
@@ -0,0 +1,16 @@
package com.baeldung.arraysums;
import com.baeldung.arraysums.SumArraysUsingStreams;
import org.junit.Test;
import static org.junit.Assert.*;
public class SumArraysUsingStreamsUnitTest {
@Test
public void sumOfTwoArraysUsingStreams_GivenTwoEqualSizedIntArrays_ReturnsCorrectSumArray() {
int[] arr1 = {4, 5, 1, 6, 4, 15};
int[] arr2 = {3, 5, 6, 1, 9, 6};
int[] expected = {7, 10, 7, 7, 13, 21};
assertArrayEquals(expected, SumArraysUsingStreams.sumOfTwoArrays(arr1, arr2));
}
}
@@ -5,3 +5,4 @@ This module contains articles about Java Character Class
### Relevant Articles:
- [Character#isAlphabetic vs. Character#isLetter](https://www.baeldung.com/java-character-isletter-isalphabetic)
- [Difference Between Javas “char” and “String”](https://www.baeldung.com/java-char-vs-string)
- [Increment Character in Java](https://www.baeldung.com/java-char-sequence)
@@ -0,0 +1,29 @@
package com.baeldung.incrementchar;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
class IncrementCharUnitTest {
@Test
void whenUsingForLoop_thenGenerateCharacters(){
final List<Character> allCapitalCharacters = Arrays.asList('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
List<Character> characters = new ArrayList<>();
for (char character = 'A'; character <= 'Z'; character++) {
characters.add(character);
}
Assertions.assertEquals(characters, allCapitalCharacters);
}
@Test
void whenUsingStreams_thenGenerateCharacters() {
final List<Character> allCapitalCharacters = Arrays.asList('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
final List<Character> characters = IntStream.rangeClosed('A', 'Z').mapToObj(c -> (char) c).collect(Collectors.toList());
Assertions.assertEquals(characters, allCapitalCharacters);
}
}
@@ -5,4 +5,6 @@
### Relevant Articles:
- [Introduction to Roaring Bitmap](https://www.baeldung.com/java-roaring-bitmap-intro)
- [Creating Custom Iterator in Java](https://www.baeldung.com/java-creating-custom-iterator)
- [Difference Between Arrays.sort() and Collections.sort()](https://www.baeldung.com/java-arrays-collections-sort-methods)
- [Skipping the First Iteration in Java](https://www.baeldung.com/java-skip-first-iteration)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-4)
@@ -0,0 +1,26 @@
package com.baeldung.collectionsvsarrays;
import com.baeldung.collectionsvsarrays.sorting.Quicksort;
import java.util.Comparator;
import java.util.List;
public class NonStableSortExample {
public static void main(String[] args) {
List<Task> tasks = Tasks.supplier.get();
Quicksort.sort(tasks, Comparator.comparingInt(Task::getPriority));
System.out.println("After sorting by priority:");
for (Task task : tasks) {
System.out.println(task);
}
Quicksort.sort(tasks, Comparator.comparing(Task::getDueDate));
System.out.println("\nAfter sorting by due date:");
for (Task task : tasks) {
System.out.println(task);
}
}
}
@@ -0,0 +1,56 @@
package com.baeldung.collectionsvsarrays;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
@Measurement(iterations = 2, time = 10, timeUnit = TimeUnit.MINUTES)
@Warmup(iterations = 5, time = 10)
@Fork(value = 2)
public class ObjectOverheadBenchmark {
private static final ThreadLocalRandom RANDOM = ThreadLocalRandom.current();
@State(Scope.Benchmark)
public static class Input {
public Supplier<List<Integer>> randomNumbers = () -> RANDOM.ints().limit(10000).boxed().collect(Collectors.toList());
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void sortingPrimitiveArray(Input input, Blackhole blackhole) {
final int[] array = input.randomNumbers.get().stream().mapToInt(Integer::intValue).toArray();
Arrays.sort(array);
final List<Integer> result = Arrays.stream(array).boxed().collect(Collectors.toList());
blackhole.consume(result);
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void sortingObjectArray(Input input, Blackhole blackhole) {
final Integer[] array = input.randomNumbers.get().toArray(new Integer[0]);
Arrays.sort(array);
blackhole.consume(array);
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void sortingObjects(Input input, Blackhole blackhole) {
final List<Integer> list = input.randomNumbers.get();
Collections.sort(list);
blackhole.consume(list);
}
}
@@ -0,0 +1,51 @@
package com.baeldung.collectionsvsarrays;
import com.baeldung.collectionsvsarrays.sorting.MergeSort;
import com.baeldung.collectionsvsarrays.sorting.Quicksort;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.IntStream;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Warmup;
@Measurement(iterations = 2, time = 10, timeUnit = TimeUnit.MINUTES)
@Warmup(iterations = 5, time = 10)
public class PerformanceBenchmark {
private static final Random RANDOM = new Random();
private static final int ARRAY_SIZE = 10000;
private static final int[] randomNumbers = RANDOM.ints(ARRAY_SIZE).toArray();
private static final int[] sameNumbers = IntStream.generate(() -> 42).limit(ARRAY_SIZE).toArray();
public static final Supplier<int[]> randomNumbersSupplier = randomNumbers::clone;
public static final Supplier<int[]> sameNumbersSupplier = sameNumbers::clone;
@Benchmark
@BenchmarkMode(Mode.Throughput)
@Fork(value = 1, jvmArgs = {"-Xlog:gc:file=gc-logs-quick-sort-same-number-%t.txt,filesize=900m -Xmx6gb -Xms6gb"})
public void quickSortSameNumber() {
Quicksort.sort(sameNumbersSupplier.get());
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
@Fork(value = 1, jvmArgs = {"-Xlog:gc:file=gc-logs-quick-sort-random-number-%t.txt,filesize=900m -Xmx6gb -Xms6gb"})
public void quickSortRandomNumber() {
Quicksort.sort(randomNumbersSupplier.get());
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
@Fork(value = 1, jvmArgs = {"-Xlog:gc:file=gc-logs-merge-sort-same-number-%t.txt,filesize=900m -Xmx6gb -Xms6gb"})
public void mergeSortSameNumber() {
MergeSort.sort(sameNumbersSupplier.get());
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
@Fork(value = 1, jvmArgs = {"-Xlog:gc:file=gc-logs-merge-sort-random-number-%t.txt,filesize=900m -Xmx6gb -Xms6gb"})
public void mergeSortRandomNumber() {
MergeSort.sort(randomNumbersSupplier.get());
}
}
@@ -0,0 +1,23 @@
package com.baeldung.collectionsvsarrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class StableSortExample {
public static void main(String[] args) {
final List<Task> tasks = Tasks.supplier.get();
Collections.sort(tasks, Comparator.comparingInt(Task::getPriority));
System.out.println("After sorting by priority:");
for (Task task : tasks) {
System.out.println(task);
}
Collections.sort(tasks, Comparator.comparing(Task::getDueDate));
System.out.println("\nAfter sorting by due date:");
for (Task task : tasks) {
System.out.println(task);
}
}
}
@@ -0,0 +1,30 @@
package com.baeldung.collectionsvsarrays;
public class Task {
private final long id;
private final int priority;
private final String dueDate;
public Task(final long id, int priority, String dueDate) {
this.id = id;
this.priority = priority;
this.dueDate = dueDate;
}
@Override
public String toString() {
return String.format("Task: #%-2d | Priority: %d | Due Date: %s", getId(), getPriority(), getDueDate());
}
public int getPriority() {
return priority;
}
public String getDueDate() {
return dueDate;
}
private long getId() {
return id;
}
}
@@ -0,0 +1,30 @@
package com.baeldung.collectionsvsarrays;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
public class Tasks {
private static final List<Task> tasks;
public static final Supplier<List<Task>> supplier;
static {
tasks = new ArrayList<>();
tasks.add(new Task(1, 1, "2023-09-01"));
tasks.add(new Task(2, 2, "2023-08-30"));
tasks.add(new Task(3, 1, "2023-08-29"));
tasks.add(new Task(4, 2, "2023-09-02"));
tasks.add(new Task(5, 3, "2023-09-05"));
tasks.add(new Task(6, 1, "2023-09-03"));
tasks.add(new Task(7, 3, "2023-08-28"));
tasks.add(new Task(8, 2, "2023-09-01"));
tasks.add(new Task(9, 1, "2023-08-28"));
tasks.add(new Task(10, 2, "2023-09-04"));
tasks.add(new Task(11, 3, "2023-08-31"));
tasks.add(new Task(12, 1, "2023-08-30"));
tasks.add(new Task(13, 3, "2023-09-02"));
supplier = () -> new ArrayList<>(tasks);
}
}
@@ -0,0 +1,47 @@
package com.baeldung.collectionsvsarrays.sorting;
public class MergeSort {
public static void sort(int[] a) {
sort(a, a.length);
}
public static void sort(int[] a, int n) {
if (n < 2) {
return;
}
int mid = n / 2;
int[] l = new int[mid];
int[] r = new int[n - mid];
for (int i = 0; i < mid; i++) {
l[i] = a[i];
}
for (int i = mid; i < n; i++) {
r[i - mid] = a[i];
}
sort(l, mid);
sort(r, n - mid);
merge(a, l, r, mid, n - mid);
}
private static void merge(
int[] a, int[] l, int[] r, int left, int right) {
int i = 0, j = 0, k = 0;
while (i < left && j < right) {
if (l[i] <= r[j]) {
a[k++] = l[i++];
}
else {
a[k++] = r[j++];
}
}
while (i < left) {
a[k++] = l[i++];
}
while (j < right) {
a[k++] = r[j++];
}
}
}
@@ -0,0 +1,72 @@
package com.baeldung.collectionsvsarrays.sorting;
import java.util.Comparator;
import java.util.List;
public class Quicksort {
public static void sort(int arr[]) {
sort(arr, 0, arr.length - 1);
}
public static void sort(int arr[], int begin, int end) {
if (begin < end) {
int partitionIndex = partition(arr, begin, end);
sort(arr, begin, partitionIndex-1);
sort(arr, partitionIndex+1, end);
}
}
private static int partition(int arr[], int begin, int end) {
int pivot = arr[end];
int i = (begin-1);
for (int j = begin; j < end; j++) {
if (arr[j] <= pivot) {
i++;
int swapTemp = arr[i];
arr[i] = arr[j];
arr[j] = swapTemp;
}
}
int swapTemp = arr[i+1];
arr[i+1] = arr[end];
arr[end] = swapTemp;
return i+1;
}
public static <T> void sort(List<T> list, Comparator<T> comparator) {
sort(list, 0, list.size() - 1, comparator);
}
public static <T> void sort(List<T> list, int low, int high, Comparator<T> comparator) {
if (low < high) {
int partitionIndex = partition(list, low, high, comparator);
sort(list, low, partitionIndex - 1, comparator);
sort(list, partitionIndex + 1, high, comparator);
}
}
private static <T> int partition(List<T> list, int begin, int end, Comparator<T> comparator) {
T pivot = list.get(end);
int i = (begin-1);
for (int j = begin; j < end; j++) {
if (comparator.compare(list.get(j), pivot) <= 0) {
i++;
T swapTemp = list.get(i);
list.set(i, list.get(j));
list.set(j, swapTemp);
}
}
T swapTemp = list.get(i+1);
list.set(i+1,list.get(end));
list.set(end, swapTemp);
return i+1;
}
}
@@ -0,0 +1,126 @@
package com.baeldung.skippingfirstelement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class SkipFirstElementExample {
private final List<String> stringList = new ArrayList<>();
private final Set<String> stringSet = new HashSet<>();
private final Map<String, String> stringMap = new HashMap<>();
public SkipFirstElementExample() {
// Initializing a List
stringList.add("Monday");
stringList.add("Tuesday");
stringList.add("Wednesday");
stringList.add("Thursday");
stringList.add("Friday");
stringList.add("Saturday");
stringList.add("Sunday");
// Initializing a Set
stringSet.add("Monday");
stringSet.add("Tuesday");
stringSet.add("Wednesday");
stringSet.add("Thursday");
stringSet.add("Friday");
stringSet.add("Saturday");
stringSet.add("Sunday");
// Initializing a Map
stringMap.put("Monday", "The day when coffee is a life support system.");
stringMap.put("Tuesday", "The day you realize that Monday's optimism was a lie.");
stringMap.put("Wednesday", "Hump Day, or as it's known, the 'Is it Friday yet?' day.");
stringMap.put("Thursday", "The day that says, 'Hold my beer, Friday is coming!'");
stringMap.put("Friday", "The golden child of the weekdays. The superhero of the workweek.");
stringMap.put("Saturday", "The day of rest? More like the day of 'What can I binge-watch next?'");
stringMap.put("Sunday", "The day before you have to adult again.");
}
void skippingFirstElementInListWithForLoop(List<String> stringList) {
for (int i = 1; i < stringList.size(); i++) {
process(stringList.get(i));
}
}
void skippingFirstElementInListWithWhileLoop(List<String> stringList) {
final Iterator<String> iterator = stringList.iterator();
if (iterator.hasNext()) {
iterator.next();
}
while (iterator.hasNext()) {
process(iterator.next());
}
}
void skippingFirstElementInSetWithWhileLoop(Set<String> stringSet) {
final Iterator<String> iterator = stringSet.iterator();
if (iterator.hasNext()) {
iterator.next();
}
while (iterator.hasNext()) {
process(iterator.next());
}
}
void skippingFirstElementInListWithWhileLoopStoringFirstElement(List<String> stringList) {
final Iterator<String> iterator = stringList.iterator();
String firstElement = null;
if (iterator.hasNext()) {
firstElement = iterator.next();
}
while (iterator.hasNext()) {
process(iterator.next());
// additional logic using fistElement
}
}
void skippingFirstElementInMapWithStreamSkip(Map<String, String> stringMap) {
stringMap.entrySet().stream().skip(1).forEach(this::process);
}
void skippingFirstElementInListWithSubList(List<String> stringList) {
for (final String element : stringList.subList(1, stringList.size())) {
process(element);
}
}
void skippingFirstElementInListWithForLoopWithAdditionalCheck(List<String> stringList) {
for (int i = 0; i < stringList.size(); i++) {
if (i == 0) {
// do something else
} else {
process(stringList.get(i));
}
}
}
void skippingFirstElementInListWithWhileLoopWithCounter(List<String> stringList) {
int counter = 0;
while (counter < stringList.size()) {
if (counter != 0) {
process(stringList.get(counter));
}
++counter;
}
}
void skippingFirstElementInListWithReduce(List<String> stringList) {
stringList.stream().reduce((skip, element) -> {
process(element);
return element;
});
}
protected void process(String string) {
System.out.println(string);
}
protected void process(Entry<String, String> mapEntry) {
System.out.println(mapEntry);
}
}
@@ -0,0 +1,122 @@
package com.baeldung.skippingfirstelement;
import static org.junit.jupiter.api.Assertions.*;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.condition.EnabledForJreRange;
import org.junit.jupiter.api.condition.JRE;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
@EnabledForJreRange(min = JRE.JAVA_9)
class SkipFirstElementExampleUnitTest {
private static TestableSkipFirstElement testableSkip = new TestableSkipFirstElement();
@BeforeEach
void setup() {
testableSkip.reset();
}
private static Stream<Arguments> listProvider() {
return Stream.of(
Arguments.of(
List.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"),
List.of("Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"))
);
}
private static Stream<Arguments> mapProvider() {
return Stream.of(
Arguments.of(
Map.of(
"Monday", "The day when coffee is a life support system.",
"Tuesday", "The day you realize that Monday's optimism was a lie.",
"Wednesday", "Hump Day, or as it's known, the 'Is it Friday yet?' day.",
"Thursday", "The day that says, 'Hold my beer, Friday is coming!'",
"Friday", "The golden child of the weekdays. The superhero of the workweek.",
"Saturday", "The day of rest? More like the day of 'What can I binge-watch next?'",
"Sunday", "The day before you have to adult again."
)
)
);
}
@ParameterizedTest
@MethodSource("listProvider")
void skippingFirstElementInListWithForLoop(List<String> input, List<String> expected) {
testableSkip.skippingFirstElementInListWithForLoop(input);
List<?> actual = testableSkip.getResult();
assertEquals(actual, expected);
}
@ParameterizedTest
@MethodSource("listProvider")
void skippingFirstElementInListWithWhileLoop(List<String> input, List<String> expected) {
testableSkip.skippingFirstElementInListWithWhileLoop(input);
List<?> actual = testableSkip.getResult();
assertEquals(actual, expected);
}
@ParameterizedTest
@MethodSource("listProvider")
void skippingFirstElementInSetWithWhileLoop(List<String> input) {
testableSkip.skippingFirstElementInSetWithWhileLoop(new HashSet<>(input));
Set<?> actual = new HashSet<>(testableSkip.getResult());
assertEquals(actual.size(), input.size() - 1);
}
@ParameterizedTest
@MethodSource("listProvider")
void skippingFirstElementInListWithWhileLoopStoringFirstElement(List<String> input, List<String> expected) {
testableSkip.skippingFirstElementInListWithWhileLoopStoringFirstElement(input);
List<?> actual = testableSkip.getResult();
assertEquals(actual, expected);
}
@ParameterizedTest
@MethodSource("mapProvider")
void skippingFirstElementInMapWithStreamSkip(Map<String, String> input) {
testableSkip.skippingFirstElementInMapWithStreamSkip(input);
List<?> actual = testableSkip.getResult();
assertEquals(actual.size(), input.size() - 1);
}
@ParameterizedTest
@MethodSource("listProvider")
void skippingFirstElementInListWithSubList(List<String> input, List<String> expected) {
testableSkip.skippingFirstElementInListWithSubList(input);
List<?> actual = testableSkip.getResult();
assertEquals(actual, expected);
}
@ParameterizedTest
@MethodSource("listProvider")
void skippingFirstElementInListWithForLoopWithAdditionalCheck(List<String> input, List<String> expected) {
testableSkip.skippingFirstElementInListWithForLoopWithAdditionalCheck(input);
List<?> actual = testableSkip.getResult();
assertEquals(actual, expected);
}
@ParameterizedTest
@MethodSource("listProvider")
void skippingFirstElementInListWithWhileLoopWithCounter(List<String> input, List<String> expected) {
testableSkip.skippingFirstElementInListWithWhileLoopWithCounter(input);
List<?> actual = testableSkip.getResult();
assertEquals(actual, expected);
}
@ParameterizedTest
@MethodSource("listProvider")
void skippingFirstElementInListWithReduce(List<String> input, List<String> expected) {
testableSkip.skippingFirstElementInListWithReduce(input);
List<?> actual = testableSkip.getResult();
assertEquals(actual, expected);
}
}
@@ -0,0 +1,10 @@
package com.baeldung.skippingfirstelement;
import java.util.List;
public interface TestableSkip {
void reset();
List<?> getResult();
}
@@ -0,0 +1,37 @@
package com.baeldung.skippingfirstelement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
public class TestableSkipFirstElement extends SkipFirstElementExample implements TestableSkip {
private List<String> processedList = new ArrayList<>();
private List<Entry<String, String>> processedEntryList = new ArrayList<>();
@Override
public void process(String string) {
processedList.add(string);
}
@Override
public void process(Entry<String, String> stringEntry) {
processedEntryList.add(stringEntry);
}
@Override
public void reset() {
processedList.clear();
processedEntryList.clear();
}
@Override
public List<?> getResult() {
if (!processedList.isEmpty())
return processedList;
return processedEntryList;
}
}
@@ -0,0 +1,6 @@
## Core Java Collections ArrayList
This module contains articles about the Java ArrayList collection
### Relevant Articles:
- [Create an ArrayList with Multiple Object Types](https://www.baeldung.com/java-arraylist-multiple-object-types)
@@ -0,0 +1,32 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-collections-array-list-2</artifactId>
<name>core-java-collections-array-list-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${maven-compiler-plugin.source}</source>
<target>${maven-compiler-plugin.target}</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven-compiler-plugin.source>17</maven-compiler-plugin.source>
<maven-compiler-plugin.target>17</maven-compiler-plugin.target>
</properties>
</project>
@@ -0,0 +1,51 @@
package com.baeldung.list.multipleobjecttypes;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.function.Predicate;
public class AlternativeMultipeTypeList {
public static void main(String[] args) {
// List of Parent Class
ArrayList<Number> myList = new ArrayList<>();
myList.add(1.2);
myList.add(2);
myList.add(-3.5);
// List of Interface type
ArrayList<Map> diffMapList = new ArrayList<>();
diffMapList.add(new HashMap<>());
diffMapList.add(new TreeMap<>());
diffMapList.add(new LinkedHashMap<>());
// List of Custom Object
ArrayList<CustomObject> objList = new ArrayList<>();
objList.add(new CustomObject("String"));
objList.add(new CustomObject(2));
// List via Functional Interface
List<Object> dataList = new ArrayList<>();
Predicate<Object> myPredicate = inputData -> (inputData instanceof String || inputData instanceof Integer);
UserFunctionalInterface myInterface = (listObj, data) -> {
if (myPredicate.test(data))
listObj.add(data);
else
System.out.println("Skipping input as data not allowed for class: " + data.getClass()
.getSimpleName());
return listObj;
};
myInterface.addToList(dataList, Integer.valueOf(2));
myInterface.addToList(dataList, Double.valueOf(3.33));
myInterface.addToList(dataList, "String Value");
myInterface.printList(dataList);
}
}
@@ -0,0 +1,22 @@
package com.baeldung.list.multipleobjecttypes;
public class CustomObject {
String classData;
Integer intData;
CustomObject(String classData) {
this.classData = classData;
}
CustomObject(Integer intData) {
this.intData = intData;
}
public String getClassData() {
return this.classData;
}
public Integer getIntData() {
return this.intData;
}
}
@@ -0,0 +1,40 @@
package com.baeldung.list.multipleobjecttypes;
import java.math.BigInteger;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MultipleObjectTypeArrayList {
public static void main(String[] args) {
ArrayList<Object> multiTypeList = new ArrayList<>();
multiTypeList.add(Integer.valueOf(10));
multiTypeList.add(Double.valueOf(11.5));
multiTypeList.add("String Data");
multiTypeList.add(Arrays.asList(1, 2, 3));
multiTypeList.add(new CustomObject("Class Data"));
multiTypeList.add(BigInteger.valueOf(123456789));
multiTypeList.add(LocalDate.of(2023, 9, 19));
for (Object dataObj : multiTypeList) {
if (dataObj instanceof Integer intData)
System.out.println("Integer Data : " + intData);
else if (dataObj instanceof Double doubleData)
System.out.println("Double Data : " + doubleData);
else if (dataObj instanceof String stringData)
System.out.println("String Data : " + stringData);
else if (dataObj instanceof List<?> intList)
System.out.println("List Data : " + intList);
else if (dataObj instanceof CustomObject customObj)
System.out.println("CustomObject Data : " + customObj.getClassData());
else if (dataObj instanceof BigInteger bigIntData)
System.out.println("BigInteger Data : " + bigIntData);
else if (dataObj instanceof LocalDate localDate)
System.out.println("LocalDate Data : " + localDate.toString());
}
}
}
@@ -0,0 +1,18 @@
package com.baeldung.list.multipleobjecttypes;
import java.util.List;
@FunctionalInterface
public interface UserFunctionalInterface {
List<Object> addToList(List<Object> list, Object data);
default void printList(List<Object> dataList) {
for (Object data : dataList) {
if (data instanceof String stringData)
System.out.println("String Data: " + stringData);
if (data instanceof Integer intData)
System.out.println("Integer Data: " + intData);
}
}
}
@@ -12,4 +12,6 @@ This module contains articles about conversions among Collection types and array
- [Convert a List of Integers to a List of Strings](https://www.baeldung.com/java-convert-list-integers-to-list-strings)
- [Combining Two Lists Into a Map in Java](https://www.baeldung.com/java-combine-two-lists-into-map)
- [Convert a List of Strings to a List of Integers](https://www.baeldung.com/java-convert-list-strings-to-integers)
- [Convert List to Long[] Array in Java](https://www.baeldung.com/java-convert-list-object-to-long-array)
- [Get the First n Elements of a List Into an Array](https://www.baeldung.com/java-take-start-elements-list-array)
- More articles: [[<-- prev]](../core-java-collections-conversions)

Some files were not shown because too many files have changed in this diff Show More