Skip to content

Commit bbc4cdd

Browse files
committed
Merge branch 'master' of https://github.com/eugenp/tutorials into task/BAEL-9709
2 parents 8c36133 + 362bd20 commit bbc4cdd

47 files changed

Lines changed: 1330 additions & 95 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎algorithms/src/main/java/com/baeldung/algorithms/bubblesort/BubbleSort.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ public class BubbleSort {
77
void bubbleSort(Integer[] arr) {
88
int n = arr.length;
99
IntStream.range(0, n - 1)
10-
.flatMap(i -> IntStream.range(i + 1, n - i))
10+
.flatMap(i -> IntStream.range(1, n - i))
1111
.forEach(j -> {
1212
if (arr[j - 1] > arr[j]) {
1313
int temp = arr[j];

‎algorithms/src/test/java/com/baeldung/algorithms/bubblesort/BubbleSortUnitTest.java‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
package com.baeldung.algorithms.bubblesort;
22

3-
import static org.junit.Assert.*;
3+
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
44

5-
import org.junit.Test;
5+
import org.junit.jupiter.api.Test;
66

77
public class BubbleSortUnitTest {
88

‎core-java-8/src/test/java/com/baeldung/java8/Java8ForEachUnitTest.java‎

Lines changed: 68 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,20 @@
11
package com.baeldung.java8;
22

3-
import org.junit.Test;
4-
import org.slf4j.Logger;
5-
import org.slf4j.LoggerFactory;
6-
3+
import java.util.ArrayDeque;
74
import java.util.ArrayList;
5+
import java.util.Arrays;
6+
import java.util.HashMap;
7+
import java.util.HashSet;
88
import java.util.List;
9+
import java.util.Map;
10+
import java.util.Queue;
11+
import java.util.Set;
912
import java.util.function.Consumer;
1013

14+
import org.junit.Test;
15+
import org.slf4j.Logger;
16+
import org.slf4j.LoggerFactory;
17+
1118
public class Java8ForEachUnitTest {
1219

1320
private static final Logger LOG = LoggerFactory.getLogger(Java8ForEachUnitTest.class);
@@ -29,8 +36,18 @@ public void compareForEachMethods_thenPrintResults() {
2936
}
3037

3138
// Java 8 - forEach
32-
LOG.debug("--- forEach method ---");
33-
names.forEach(name -> LOG.debug(name));
39+
names.forEach(name -> {
40+
System.out.println(name);
41+
});
42+
43+
LOG.debug("--- Print Consumer ---");
44+
Consumer<String> printConsumer = new Consumer<String>() {
45+
public void accept(String name) {
46+
System.out.println(name);
47+
};
48+
};
49+
50+
names.forEach(printConsumer);
3451

3552
// Anonymous inner class that implements Consumer interface
3653
LOG.debug("--- Anonymous inner class ---");
@@ -40,17 +57,55 @@ public void accept(String name) {
4057
}
4158
});
4259

43-
// Create a Consumer implementation to then use in a forEach method
44-
Consumer<String> consumerNames = name -> {
45-
LOG.debug(name);
46-
};
47-
LOG.debug("--- Implementation of Consumer interface ---");
48-
names.forEach(consumerNames);
60+
// Java 8 - forEach - Lambda Syntax
61+
LOG.debug("--- forEach method ---");
62+
names.forEach(name -> LOG.debug(name));
4963

50-
// Print elements using a Method Reference
64+
// Java 8 - forEach - Print elements using a Method Reference
5165
LOG.debug("--- Method Reference ---");
5266
names.forEach(LOG::debug);
67+
}
68+
69+
@Test
70+
public void givenList_thenIterateAndPrintResults() {
71+
List<String> names = Arrays.asList("Larry", "Steve", "James");
72+
73+
names.forEach(System.out::println);
74+
}
75+
76+
@Test
77+
public void givenSet_thenIterateAndPrintResults() {
78+
Set<String> uniqueNames = new HashSet<>(Arrays.asList("Larry", "Steve", "James"));
79+
80+
uniqueNames.forEach(System.out::println);
81+
}
82+
83+
@Test
84+
public void givenQueue_thenIterateAndPrintResults() {
85+
Queue<String> namesQueue = new ArrayDeque<>(Arrays.asList("Larry", "Steve", "James"));
86+
87+
namesQueue.forEach(System.out::println);
88+
}
89+
90+
@Test
91+
public void givenMap_thenIterateAndPrintResults() {
92+
Map<Integer, String> namesMap = new HashMap<>();
93+
namesMap.put(1, "Larry");
94+
namesMap.put(2, "Steve");
95+
namesMap.put(3, "James");
96+
97+
namesMap.entrySet()
98+
.forEach(entry -> System.out.println(entry.getKey() + " " + entry.getValue()));
99+
}
100+
101+
@Test
102+
public void givenMap_whenUsingBiConsumer_thenIterateAndPrintResults2() {
103+
Map<Integer, String> namesMap = new HashMap<>();
104+
namesMap.put(1, "Larry");
105+
namesMap.put(2, "Steve");
106+
namesMap.put(3, "James");
53107

108+
namesMap.forEach((key, value) -> System.out.println(key + " " + value));
54109
}
55110

56111
}

‎core-java-io/pom.xml‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,12 @@
154154
<artifactId>async-http-client</artifactId>
155155
<version>${async-http-client.version}</version>
156156
</dependency>
157+
<dependency>
158+
<groupId>com.opencsv</groupId>
159+
<artifactId>opencsv</artifactId>
160+
<version>${opencsv.version}</version>
161+
<scope>test</scope>
162+
</dependency>
157163
</dependencies>
158164

159165
<build>
@@ -247,7 +253,7 @@
247253
<protonpack.version>1.13</protonpack.version>
248254
<streamex.version>0.6.5</streamex.version>
249255
<vavr.version>0.9.0</vavr.version>
250-
256+
<opencsv.version>4.1</opencsv.version>
251257
<!-- testing -->
252258
<assertj.version>3.6.1</assertj.version>
253259
<avaitility.version>1.7.0</avaitility.version>

‎core-java-io/src/main/java/com/baeldung/unzip/UnzipFile.java‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,13 @@
99

1010
public class UnzipFile {
1111
public static void main(final String[] args) throws IOException {
12-
final String fileZip = "src/main/resources/compressed.zip";
12+
final String fileZip = "src/main/resources/unzipTest/compressed.zip";
13+
final File destDir = new File("src/main/resources/unzipTest");
1314
final byte[] buffer = new byte[1024];
1415
final ZipInputStream zis = new ZipInputStream(new FileInputStream(fileZip));
1516
ZipEntry zipEntry = zis.getNextEntry();
1617
while (zipEntry != null) {
17-
final String fileName = zipEntry.getName();
18-
final File newFile = new File("src/main/resources/unzipTest/" + fileName);
18+
final File newFile = newFile(destDir, zipEntry);
1919
final FileOutputStream fos = new FileOutputStream(newFile);
2020
int len;
2121
while ((len = zis.read(buffer)) > 0) {
@@ -27,4 +27,20 @@ public static void main(final String[] args) throws IOException {
2727
zis.closeEntry();
2828
zis.close();
2929
}
30+
31+
/**
32+
* @see https://snyk.io/research/zip-slip-vulnerability
33+
*/
34+
public static File newFile(File destinationDir, ZipEntry zipEntry) throws IOException {
35+
File destFile = new File(destinationDir, zipEntry.getName());
36+
37+
String destDirPath = destinationDir.getCanonicalPath();
38+
String destFilePath = destFile.getCanonicalPath();
39+
40+
if (!destFilePath.startsWith(destDirPath + File.separator)) {
41+
throw new IOException("Entry is outside of the target dir: " + zipEntry.getName());
42+
}
43+
44+
return destFile;
45+
}
3046
}
256 Bytes
Binary file not shown.
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
package com.baeldung.csv;
2+
3+
import java.io.BufferedReader;
4+
import java.io.File;
5+
import java.io.FileNotFoundException;
6+
import java.io.FileReader;
7+
import java.io.IOException;
8+
import java.util.ArrayList;
9+
import java.util.Arrays;
10+
import java.util.Collections;
11+
import java.util.List;
12+
import java.util.Scanner;
13+
14+
import org.junit.Assert;
15+
import org.junit.Test;
16+
17+
import com.opencsv.CSVReader;
18+
19+
public class ReadCSVInArrayUnitTest {
20+
public static final String COMMA_DELIMITER = ",";
21+
public static final String CSV_FILE = "src/test/resources/book.csv";
22+
public static final List<List<String>> EXPECTED_ARRAY = Collections.unmodifiableList(new ArrayList<List<String>>() {
23+
{
24+
add(new ArrayList<String>() {
25+
{
26+
add("Mary Kom");
27+
add("Unbreakable");
28+
}
29+
});
30+
add(new ArrayList<String>() {
31+
{
32+
add("Kapil Isapuari");
33+
add("Farishta");
34+
}
35+
});
36+
}
37+
});
38+
39+
@Test
40+
public void givenCSVFile_whenBufferedReader_thenContentsAsExpected() throws IOException {
41+
List<List<String>> records = new ArrayList<List<String>>();
42+
try (BufferedReader br = new BufferedReader(new FileReader(CSV_FILE))) {
43+
String line = "";
44+
while ((line = br.readLine()) != null) {
45+
String[] values = line.split(COMMA_DELIMITER);
46+
records.add(Arrays.asList(values));
47+
}
48+
} catch (Exception e) {
49+
e.printStackTrace();
50+
}
51+
for (int i = 0; i < EXPECTED_ARRAY.size(); i++) {
52+
Assert.assertArrayEquals(EXPECTED_ARRAY.get(i)
53+
.toArray(),
54+
records.get(i)
55+
.toArray());
56+
}
57+
}
58+
59+
@Test
60+
public void givenCSVFile_whenScanner_thenContentsAsExpected() throws IOException {
61+
List<List<String>> records = new ArrayList<List<String>>();
62+
try (Scanner scanner = new Scanner(new File(CSV_FILE));) {
63+
while (scanner.hasNextLine()) {
64+
records.add(getRecordFromLine(scanner.nextLine()));
65+
}
66+
} catch (FileNotFoundException e) {
67+
e.printStackTrace();
68+
}
69+
for (int i = 0; i < EXPECTED_ARRAY.size(); i++) {
70+
Assert.assertArrayEquals(EXPECTED_ARRAY.get(i)
71+
.toArray(),
72+
records.get(i)
73+
.toArray());
74+
}
75+
}
76+
77+
private List<String> getRecordFromLine(String line) {
78+
List<String> values = new ArrayList<String>();
79+
try (Scanner rowScanner = new Scanner(line)) {
80+
rowScanner.useDelimiter(COMMA_DELIMITER);
81+
while (rowScanner.hasNext()) {
82+
values.add(rowScanner.next());
83+
}
84+
}
85+
return values;
86+
}
87+
88+
@Test
89+
public void givenCSVFile_whenOpencsv_thenContentsAsExpected() throws IOException {
90+
List<List<String>> records = new ArrayList<List<String>>();
91+
try (CSVReader csvReader = new CSVReader(new FileReader(CSV_FILE));) {
92+
String[] values = null;
93+
while ((values = csvReader.readNext()) != null) {
94+
records.add(Arrays.asList(values));
95+
}
96+
} catch (Exception e) {
97+
e.printStackTrace();
98+
}
99+
for (int i = 0; i < EXPECTED_ARRAY.size(); i++) {
100+
Assert.assertArrayEquals(EXPECTED_ARRAY.get(i)
101+
.toArray(),
102+
records.get(i)
103+
.toArray());
104+
}
105+
}
106+
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Mary Kom,Unbreakable
2+
Kapil Isapuari,Farishta
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.baeldung.string;
2+
3+
import java.math.RoundingMode;
4+
import java.text.DecimalFormat;
5+
import java.text.NumberFormat;
6+
7+
public class DoubleToString {
8+
9+
public static String truncateByCast(double d) {
10+
return String.valueOf((int) d);
11+
}
12+
13+
public static String roundWithStringFormat(double d) {
14+
return String.format("%.0f", d);
15+
}
16+
17+
public static String truncateWithNumberFormat(double d) {
18+
NumberFormat nf = NumberFormat.getInstance();
19+
nf.setMaximumFractionDigits(0);
20+
nf.setRoundingMode(RoundingMode.FLOOR);
21+
return nf.format(d);
22+
}
23+
24+
public static String roundWithNumberFormat(double d) {
25+
NumberFormat nf = NumberFormat.getInstance();
26+
nf.setMaximumFractionDigits(0);
27+
return nf.format(d);
28+
}
29+
30+
public static String truncateWithDecimalFormat(double d) {
31+
DecimalFormat df = new DecimalFormat("#,###");
32+
df.setRoundingMode(RoundingMode.FLOOR);
33+
return df.format(d);
34+
}
35+
36+
public static String roundWithDecimalFormat(double d) {
37+
DecimalFormat df = new DecimalFormat("#,###");
38+
return df.format(d);
39+
}
40+
41+
}

‎core-java/src/test/java/com/baeldung/simpledateformat/SimpleDateFormatUnitTest.java‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package com.baeldung;
1+
package com.baeldung.simpledateformat;
22

33
import org.junit.Test;
44

@@ -32,6 +32,7 @@ public void givenSpecificDate_whenFormattedUsingDateFormat_thenCheckFormatCorrec
3232
@Test
3333
public void givenStringDate_whenParsed_thenCheckDateCorrect() throws Exception{
3434
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
35+
formatter.setTimeZone(TimeZone.getTimeZone("Europe/London"));
3536
Date myDate = new Date(233276400000L);
3637
Date parsedDate = formatter.parse("24-05-1977");
3738
assertEquals(myDate.getTime(), parsedDate.getTime());

0 commit comments

Comments
 (0)