Skip to content

Commit 45ab03c

Browse files
committed
Merge remote-tracking branch 'upstream/master'
2 parents 165c895 + d66d9fb commit 45ab03c

54 files changed

Lines changed: 180382 additions & 418 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.

‎core-java/pom.xml‎

Lines changed: 337 additions & 313 deletions
Large diffs are not rendered by default.
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package com.baeldung.algorithms;
2+
3+
import lombok.Data;
4+
5+
@Data
6+
public class City {
7+
8+
private int x;
9+
private int y;
10+
11+
public City() {
12+
this.x = (int) (Math.random() * 500);
13+
this.y = (int) (Math.random() * 500);
14+
}
15+
16+
public double distanceToCity(City city) {
17+
int x = Math.abs(getX() - city.getX());
18+
int y = Math.abs(getY() - city.getY());
19+
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
20+
}
21+
22+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package com.baeldung.algorithms;
2+
3+
public class SimulatedAnnealing {
4+
5+
private static Travel travel = new Travel(10);
6+
7+
public static double simulateAnnealing(double startingTemperature, int numberOfIterations, double coolingRate) {
8+
System.out.println("Starting SA with temperature: " + startingTemperature + ", # of iterations: " + numberOfIterations + " and colling rate: " + coolingRate);
9+
double t = startingTemperature;
10+
travel.generateInitialTravel();
11+
double bestDistance = travel.getDistance();
12+
System.out.println("Initial distance of travel: " + bestDistance);
13+
Travel bestSolution = travel;
14+
Travel currentSolution = bestSolution;
15+
16+
for (int i = 0; i < numberOfIterations; i++) {
17+
if (t > 0.1) {
18+
currentSolution.swapCities();
19+
double currentDistance = currentSolution.getDistance();
20+
if (currentDistance == 0)
21+
continue;
22+
if (currentDistance < bestDistance) {
23+
bestDistance = currentDistance;
24+
} else if (Math.exp((currentDistance - bestDistance) / t) < Math.random()) {
25+
currentSolution.revertSwap();
26+
}
27+
t *= coolingRate;
28+
}
29+
if (i % 100 == 0) {
30+
System.out.println("Iteration #" + i);
31+
}
32+
}
33+
return bestDistance;
34+
}
35+
36+
public static void main(String[] args) {
37+
System.out.println("Optimized distance for travel: " + simulateAnnealing(10, 10000, 0.9));
38+
}
39+
40+
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package com.baeldung.algorithms;
2+
3+
import java.util.ArrayList;
4+
import java.util.Collections;
5+
6+
import lombok.Data;
7+
8+
@Data
9+
public class Travel {
10+
11+
private ArrayList<City> travel = new ArrayList<>();
12+
private ArrayList<City> previousTravel = new ArrayList<>();
13+
14+
public Travel(int numberOfCities) {
15+
for (int i = 0; i < numberOfCities; i++) {
16+
travel.add(new City());
17+
}
18+
}
19+
20+
public void generateInitialTravel() {
21+
if (travel.isEmpty())
22+
new Travel(10);
23+
Collections.shuffle(travel);
24+
}
25+
26+
public void swapCities() {
27+
int a = generateRandomIndex();
28+
int b = generateRandomIndex();
29+
previousTravel = travel;
30+
travel.set(a, travel.get(b));
31+
}
32+
33+
public void revertSwap() {
34+
travel = previousTravel;
35+
}
36+
37+
private int generateRandomIndex() {
38+
return (int) (Math.random() * travel.size());
39+
}
40+
41+
public City getCity(int index) {
42+
return travel.get(index);
43+
}
44+
45+
public int getDistance() {
46+
int distance = 0;
47+
for (int index = 0; index < travel.size(); index++) {
48+
City starting = getCity(index);
49+
City destination;
50+
if (index + 1 < travel.size()) {
51+
destination = getCity(index + 1);
52+
} else {
53+
destination = getCity(0);
54+
}
55+
distance += starting.distanceToCity(destination);
56+
}
57+
return distance;
58+
}
59+
60+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package com.baeldung.algorithms;
2+
3+
import org.junit.Assert;
4+
import org.junit.Test;
5+
6+
public class SimulatedAnnealingTest {
7+
8+
@Test
9+
public void testSimulateAnnealing() {
10+
Assert.assertTrue(SimulatedAnnealing.simulateAnnealing(10, 1000, 0.9) > 0);
11+
}
12+
13+
}

‎core-java/src/test/java/com/baeldung/encoderdecoder/EncoderDecoderUnitTest.java‎

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@ public class EncoderDecoderUnitTest {
2222
private static final String testUrl = "http://www.baeldung.com?key1=value+1&key2=value%40%21%242&key3=value%253";
2323
private static final String testUrlWithPath = "http://www.baeldung.com/path+1?key1=value+1&key2=value%40%21%242&key3=value%253";
2424

25-
2625
private String encodeValue(String value) {
2726
String encoded = null;
2827
try {
@@ -59,9 +58,7 @@ public void givenRequestParam_whenUTF8Scheme_thenEncode() throws Exception {
5958
requestParams.put("key2", "value@!$2");
6059
requestParams.put("key3", "value%3");
6160

62-
String encodedURL = requestParams.keySet().stream()
63-
.map(key -> key + "=" + encodeValue(requestParams.get(key)))
64-
.collect(joining("&", "http://www.baeldung.com?", ""));
61+
String encodedURL = requestParams.keySet().stream().map(key -> key + "=" + encodeValue(requestParams.get(key))).collect(joining("&", "http://www.baeldung.com?", ""));
6562

6663
Assert.assertThat(testUrl, is(encodedURL));
6764
}
@@ -103,12 +100,9 @@ public void givenPathAndRequestParam_whenUTF8Scheme_thenEncode() throws Exceptio
103100

104101
String path = "path+1";
105102

106-
String encodedURL = requestParams.keySet().stream()
107-
.map(key -> key + "=" + encodeValue(requestParams.get(key)))
108-
.collect(joining("&", "http://www.baeldung.com/" + encodePath(path) + "?", ""));
103+
String encodedURL = requestParams.keySet().stream().map(key -> key + "=" + encodeValue(requestParams.get(key))).collect(joining("&", "http://www.baeldung.com/" + encodePath(path) + "?", ""));
109104

110105
Assert.assertThat(testUrlWithPath, is(encodedURL));
111106
}
112107

113-
114108
}

‎core-java/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java‎

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,19 +17,15 @@ public class Java8CollectionCleanupUnitTest {
1717
@Test
1818
public void givenListContainsNulls_whenFilteringParallel_thenCorrect() {
1919
final List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null);
20-
final List<Integer> listWithoutNulls = list.parallelStream()
21-
.filter(Objects::nonNull)
22-
.collect(Collectors.toList());
20+
final List<Integer> listWithoutNulls = list.parallelStream().filter(Objects::nonNull).collect(Collectors.toList());
2321

2422
assertThat(listWithoutNulls, hasSize(3));
2523
}
2624

2725
@Test
2826
public void givenListContainsNulls_whenFilteringSerial_thenCorrect() {
2927
final List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null);
30-
final List<Integer> listWithoutNulls = list.stream()
31-
.filter(Objects::nonNull)
32-
.collect(Collectors.toList());
28+
final List<Integer> listWithoutNulls = list.stream().filter(Objects::nonNull).collect(Collectors.toList());
3329

3430
assertThat(listWithoutNulls, hasSize(3));
3531
}
@@ -45,9 +41,7 @@ public void givenListContainsNulls_whenRemovingNullsWithRemoveIf_thenCorrect() {
4541
@Test
4642
public void givenListContainsDuplicates_whenRemovingDuplicatesWithJava8_thenCorrect() {
4743
final List<Integer> listWithDuplicates = Lists.newArrayList(1, 1, 2, 2, 3, 3);
48-
final List<Integer> listWithoutDuplicates = listWithDuplicates.parallelStream()
49-
.distinct()
50-
.collect(Collectors.toList());
44+
final List<Integer> listWithoutDuplicates = listWithDuplicates.parallelStream().distinct().collect(Collectors.toList());
5145

5246
assertThat(listWithoutDuplicates, hasSize(3));
5347
}
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package com.baeldung.java8;
2+
3+
import static org.junit.Assert.assertEquals;
4+
5+
import java.io.File;
6+
import java.io.IOException;
7+
import java.nio.channels.FileChannel;
8+
import java.nio.file.Path;
9+
import java.nio.file.Paths;
10+
import org.apache.commons.io.FileUtils;
11+
import org.junit.Before;
12+
import org.junit.Test;
13+
14+
public class JavaFileSizeUnitTest {
15+
private static final long EXPECTED_FILE_SIZE_IN_BYTES = 11;
16+
private String filePath;
17+
18+
@Before
19+
public void init() {
20+
final String separator = File.separator;
21+
filePath = String.join(separator, new String[] { "src", "test", "resources", "testFolder", "sample_file_1.in" });
22+
}
23+
24+
@Test
25+
public void whenGetFileSize_thenCorrect() {
26+
final File file = new File(filePath);
27+
28+
final long size = getFileSize(file);
29+
30+
assertEquals(EXPECTED_FILE_SIZE_IN_BYTES, size);
31+
}
32+
33+
@Test
34+
public void whenGetFileSizeUsingNioApi_thenCorrect() throws IOException {
35+
final Path path = Paths.get(this.filePath);
36+
final FileChannel fileChannel = FileChannel.open(path);
37+
38+
final long fileSize = fileChannel.size();
39+
40+
assertEquals(EXPECTED_FILE_SIZE_IN_BYTES, fileSize);
41+
}
42+
43+
@Test
44+
public void whenGetFileSizeUsingApacheCommonsIO_thenCorrect() {
45+
final File file = new File(filePath);
46+
47+
final long size = FileUtils.sizeOf(file);
48+
49+
assertEquals(EXPECTED_FILE_SIZE_IN_BYTES, size);
50+
}
51+
52+
@Test
53+
public void whenGetReadableFileSize_thenCorrect() {
54+
final File file = new File(filePath);
55+
56+
final long size = getFileSize(file);
57+
58+
assertEquals(EXPECTED_FILE_SIZE_IN_BYTES + " bytes", FileUtils.byteCountToDisplaySize(size));
59+
}
60+
61+
private long getFileSize(final File file) {
62+
final long length = file.length();
63+
return length;
64+
}
65+
}

‎core-java/src/test/java/com/baeldung/java8/optional/OptionalTest.java‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@ public void whenOptionalFilterWorks_thenCorrect() {
9393
boolean is2017 = yearOptional.filter(y -> y == 2017).isPresent();
9494
assertFalse(is2017);
9595
}
96+
9697
@Test
9798
public void whenFiltersWithoutOptional_thenCorrect() {
9899
assertTrue(priceIsInRange1(new Modem(10.0)));
@@ -121,12 +122,9 @@ public boolean priceIsInRange1(Modem modem) {
121122
}
122123

123124
public boolean priceIsInRange2(Modem modem2) {
124-
return Optional.ofNullable(modem2)
125-
.map(Modem::getPrice)
126-
.filter(p -> p >= 10)
127-
.filter(p -> p <= 15)
128-
.isPresent();
125+
return Optional.ofNullable(modem2).map(Modem::getPrice).filter(p -> p >= 10).filter(p -> p <= 15).isPresent();
129126
}
127+
130128
// Transforming Value With map()
131129
@Test
132130
public void givenOptional_whenMapWorks_thenCorrect() {
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package com.baeldung.java8.unix.grep;
2+
3+
import java.io.File;
4+
import java.util.List;
5+
6+
import org.junit.Before;
7+
import org.junit.Test;
8+
import org.unix4j.Unix4j;
9+
import static org.unix4j.Unix4j.*;
10+
import static org.junit.Assert.assertEquals;
11+
import org.unix4j.line.Line;
12+
import static org.unix4j.unix.Grep.*;
13+
import static org.unix4j.unix.cut.CutOption.*;
14+
15+
public class GrepWithUnix4JTest {
16+
17+
private File fileToGrep;
18+
19+
@Before
20+
public void init() {
21+
final String separator = File.separator;
22+
final String filePath = String.join(separator, new String[] { "src", "test", "resources", "dictionary.in" });
23+
fileToGrep = new File(filePath);
24+
}
25+
26+
@Test
27+
public void whenGrepWithSimpleString_thenCorrect() {
28+
int expectedLineCount = 4;
29+
30+
// grep "NINETEEN" dictionary.txt
31+
List<Line> lines = Unix4j.grep("NINETEEN", fileToGrep).toLineList();
32+
33+
assertEquals(expectedLineCount, lines.size());
34+
}
35+
36+
@Test
37+
public void whenInverseGrepWithSimpleString_thenCorrect() {
38+
int expectedLineCount = 178687;
39+
40+
// grep -v "NINETEEN" dictionary.txt
41+
List<Line> lines = grep(Options.v, "NINETEEN", fileToGrep).toLineList();
42+
43+
assertEquals(expectedLineCount, lines.size());
44+
}
45+
46+
@Test
47+
public void whenGrepWithRegex_thenCorrect() {
48+
int expectedLineCount = 151;
49+
50+
// grep -c ".*?NINE.*?" dictionary.txt
51+
String patternCount = grep(Options.c, ".*?NINE.*?", fileToGrep).cut(fields, ":", 1).toStringResult();
52+
53+
assertEquals(expectedLineCount, Integer.parseInt(patternCount));
54+
}
55+
}

0 commit comments

Comments
 (0)