minor formatting cleanup

This commit is contained in:
eugenp
2017-08-24 13:11:52 +03:00
parent 74e67d6ce9
commit 1cba1b043c
194 changed files with 1147 additions and 1005 deletions

View File

@@ -19,13 +19,15 @@ public class NumbersProducer implements Runnable {
try {
generateNumbers();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
Thread.currentThread()
.interrupt();
}
}
private void generateNumbers() throws InterruptedException {
for (int i = 0; i < 100; i++) {
numbersQueue.put(ThreadLocalRandom.current().nextInt(100));
numbersQueue.put(ThreadLocalRandom.current()
.nextInt(100));
}
for (int j = 0; j < poisonPillPerProducer; j++) {
numbersQueue.put(poisonPill);

View File

@@ -27,9 +27,6 @@ public class DelayObject implements Delayed {
@Override
public String toString() {
return "{" +
"data='" + data + '\'' +
", startTime=" + startTime +
'}';
return "{" + "data='" + data + '\'' + ", startTime=" + startTime + '}';
}
}

View File

@@ -4,11 +4,11 @@ public class LuxuryCarsSpeed {
public double bugattiVeyronInMPH() {
return 268;
}
public double mcLarenInMPH() {
return 241;
}
public double astonMartinInMPH() {
return 220;
}

View File

@@ -2,6 +2,8 @@ package com.baeldung.designpatterns.adapter;
public interface LuxuryCarsSpeedAdapter {
public double bugattiVeyronInKMPH();
public double mcLarenInKMPH();
public double astonMartinInKMPH();
}

View File

@@ -5,7 +5,7 @@ import static com.baeldung.designpatterns.util.LogerUtil.LOG;
public class Blue implements Color {
@Override
public void fillColor() {
public void fillColor() {
LOG.info("Color : Blue");
}

View File

@@ -5,16 +5,14 @@ import static com.baeldung.designpatterns.util.LogerUtil.LOG;
public class DecoratorPatternDriver {
public static void main(String[] args) {
//christmas tree with just one Garland
// christmas tree with just one Garland
ChristmasTree tree1 = new Garland(new ChristmasTreeImpl());
LOG.info(tree1.decorate());
//christmas tree with two Garlands and one Bubble lights
ChristmasTree tree2 = new BubbleLights(new Garland(
new Garland(new ChristmasTreeImpl()))
);
// christmas tree with two Garlands and one Bubble lights
ChristmasTree tree2 = new BubbleLights(new Garland(new Garland(new ChristmasTreeImpl())));
LOG.info(tree2.decorate());
}
}

View File

@@ -7,14 +7,14 @@ public class ExpensiveObjectImpl implements ExpensiveObject {
public ExpensiveObjectImpl() {
heavyInitialConfiguration();
}
@Override
public void process() {
LOG.info("processing complete.");
}
private void heavyInitialConfiguration() {
LOG.info("Loading initial configuration...");
}
}

View File

@@ -43,6 +43,7 @@ public class CustomRecursiveAction extends RecursiveAction {
private void processing(String work) {
String result = work.toUpperCase();
logger.info("This result - (" + result + ") - was processed by " + Thread.currentThread().getName());
logger.info("This result - (" + result + ") - was processed by " + Thread.currentThread()
.getName());
}
}

View File

@@ -5,6 +5,6 @@ import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Greeter {
public String greet() default "";
public String greet() default "";
}

View File

@@ -44,7 +44,8 @@ public class MapIteration {
}
public void iterateUsingIteratorAndEntry(Map<String, Integer> map) {
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet()
.iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> pair = iterator.next();
System.out.println(pair.getKey() + ":" + pair.getValue());
@@ -58,7 +59,9 @@ public class MapIteration {
}
public void iterateUsingStreamAPI(Map<String, Integer> map) {
map.entrySet().stream().forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));
map.entrySet()
.stream()
.forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));
}
public void iterateKeys(Map<String, Integer> map) {

View File

@@ -8,7 +8,7 @@ public class BigIntegerImpl {
BigInteger numStarsMilkyWay = new BigInteger("8731409320171337804361260816606476");
BigInteger numStarsAndromeda = new BigInteger("5379309320171337804361260816606476");
BigInteger totalStars = numStarsMilkyWay.add(numStarsAndromeda);
}

View File

@@ -9,7 +9,8 @@ public class PersistentCookieStore implements CookieStore, Runnable {
public PersistentCookieStore() {
store = new CookieManager().getCookieStore();
// deserialize cookies into store
Runtime.getRuntime().addShutdownHook(new Thread(this));
Runtime.getRuntime()
.addShutdownHook(new Thread(this));
}
@Override

View File

@@ -14,7 +14,8 @@ public class Screenshot {
}
public void getScreenshot(int timeToWait) throws Exception {
Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit()
.getScreenSize());
Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture(rectangle);
ImageIO.write(img, "jpg", new File(path));

View File

@@ -6,16 +6,16 @@ import java.security.NoSuchAlgorithmException;
import java.util.UUID;
public class UUIDGenerator {
/**
* These are predefined UUID for name spaces
*/
private static final String NAMESPACE_DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
private static final String NAMESPACE_URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";
private static final String NAMESPACE_OID = "6ba7b812-9dad-11d1-80b4-00c04fd430c8";
private static final String NAMESPACE_X500 = "6ba7b814-9dad-11d1-80b4-00c04fd430c8";
private static final String NAMESPACE_DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
private static final String NAMESPACE_URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";
private static final String NAMESPACE_OID = "6ba7b812-9dad-11d1-80b4-00c04fd430c8";
private static final String NAMESPACE_X500 = "6ba7b814-9dad-11d1-80b4-00c04fd430c8";
private static final char[] hexArray = "0123456789ABCDEF".toCharArray();
private static final char[] hexArray = "0123456789ABCDEF".toCharArray();
public static void main(String[] args) {
try {
@@ -35,7 +35,7 @@ public class UUIDGenerator {
UUID uuid = UUID.randomUUID();
return uuid;
}
/**
* Type 3 UUID Generation
*
@@ -47,7 +47,7 @@ public class UUIDGenerator {
UUID uuid = UUID.nameUUIDFromBytes(bytes);
return uuid;
}
/**
* Type 5 UUID Generation
*
@@ -59,8 +59,7 @@ public class UUIDGenerator {
UUID uuid = type5UUIDFromBytes(bytes);
return uuid;
}
public static UUID type5UUIDFromBytes(byte[] name) {
MessageDigest md;
try {
@@ -69,27 +68,26 @@ public class UUIDGenerator {
throw new InternalError("MD5 not supported", nsae);
}
byte[] bytes = md.digest(name);
bytes[6] &= 0x0f; /* clear version */
bytes[6] |= 0x50; /* set to version 5 */
bytes[8] &= 0x3f; /* clear variant */
bytes[8] |= 0x80; /* set to IETF variant */
bytes[6] &= 0x0f; /* clear version */
bytes[6] |= 0x50; /* set to version 5 */
bytes[8] &= 0x3f; /* clear variant */
bytes[8] |= 0x80; /* set to IETF variant */
return constructType5UUID(bytes);
}
private static UUID constructType5UUID(byte[] data) {
long msb = 0;
long lsb = 0;
assert data.length == 16 : "data must be 16 bytes in length";
for (int i=0; i<8; i++)
for (int i = 0; i < 8; i++)
msb = (msb << 8) | (data[i] & 0xff);
for (int i=8; i<16; i++)
for (int i = 8; i < 16; i++)
lsb = (lsb << 8) | (data[i] & 0xff);
return new UUID(msb, lsb);
}
/**
* Unique Keys Generation Using Message Digest and Type 4 UUID
*

View File

@@ -15,7 +15,6 @@ public class CompletableFutureLongRunningUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(CompletableFutureLongRunningUnitTest.class);
@Test
public void whenRunningCompletableFutureAsynchronously_thenGetMethodWaitsForResult() throws InterruptedException, ExecutionException {
Future<String> completableFuture = calculateAsync();
@@ -27,11 +26,12 @@ public class CompletableFutureLongRunningUnitTest {
private Future<String> calculateAsync() throws InterruptedException {
CompletableFuture<String> completableFuture = new CompletableFuture<>();
Executors.newCachedThreadPool().submit(() -> {
Thread.sleep(500);
completableFuture.complete("Hello");
return null;
});
Executors.newCachedThreadPool()
.submit(() -> {
Thread.sleep(500);
completableFuture.complete("Hello");
return null;
});
return completableFuture;
}
@@ -47,11 +47,12 @@ public class CompletableFutureLongRunningUnitTest {
private Future<String> calculateAsyncWithCancellation() throws InterruptedException {
CompletableFuture<String> completableFuture = new CompletableFuture<>();
Executors.newCachedThreadPool().submit(() -> {
Thread.sleep(500);
completableFuture.cancel(false);
return null;
});
Executors.newCachedThreadPool()
.submit(() -> {
Thread.sleep(500);
completableFuture.cancel(false);
return null;
});
return completableFuture;
}
@@ -98,21 +99,24 @@ public class CompletableFutureLongRunningUnitTest {
@Test
public void whenUsingThenCompose_thenFuturesExecuteSequentially() throws ExecutionException, InterruptedException {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello").thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World"));
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello")
.thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World"));
assertEquals("Hello World", completableFuture.get());
}
@Test
public void whenUsingThenCombine_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello").thenCombine(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> s1 + s2);
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello")
.thenCombine(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> s1 + s2);
assertEquals("Hello World", completableFuture.get());
}
@Test
public void whenUsingThenAcceptBoth_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException {
CompletableFuture.supplyAsync(() -> "Hello").thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> LOG.debug(s1 + s2));
CompletableFuture.supplyAsync(() -> "Hello")
.thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> LOG.debug(s1 + s2));
}
@Test
@@ -131,7 +135,9 @@ public class CompletableFutureLongRunningUnitTest {
assertTrue(future2.isDone());
assertTrue(future3.isDone());
String combined = Stream.of(future1, future2, future3).map(CompletableFuture::join).collect(Collectors.joining(" "));
String combined = Stream.of(future1, future2, future3)
.map(CompletableFuture::join)
.collect(Collectors.joining(" "));
assertEquals("Hello Beautiful World", combined);
}
@@ -147,7 +153,8 @@ public class CompletableFutureLongRunningUnitTest {
throw new RuntimeException("Computation error!");
}
return "Hello, " + name;
}).handle((s, t) -> s != null ? s : "Hello, Stranger!");
})
.handle((s, t) -> s != null ? s : "Hello, Stranger!");
assertEquals("Hello, Stranger!", completableFuture.get());
}

View File

@@ -15,7 +15,9 @@ public class UseLocalDateTimeUnitTest {
@Test
public void givenString_whenUsingParse_thenLocalDateTime() {
assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalDate());
assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalTime());
assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30")
.toLocalDate());
assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30")
.toLocalTime());
}
}

View File

@@ -15,12 +15,14 @@ public class UseLocalDateUnitTest {
@Test
public void givenValues_whenUsingFactoryOf_thenLocalDate() {
assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10).toString());
assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10)
.toString());
}
@Test
public void givenString_whenUsingParse_thenLocalDate() {
assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10").toString());
assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10")
.toString());
}
@Test
@@ -30,12 +32,14 @@ public class UseLocalDateUnitTest {
@Test
public void givenDate_whenUsingPlus_thenNextDay() {
assertEquals(LocalDate.now().plusDays(1), useLocalDate.getNextDay(LocalDate.now()));
assertEquals(LocalDate.now()
.plusDays(1), useLocalDate.getNextDay(LocalDate.now()));
}
@Test
public void givenDate_whenUsingMinus_thenPreviousDay() {
assertEquals(LocalDate.now().minusDays(1), useLocalDate.getPreviousDay(LocalDate.now()));
assertEquals(LocalDate.now()
.minusDays(1), useLocalDate.getPreviousDay(LocalDate.now()));
}
@Test
@@ -45,7 +49,8 @@ public class UseLocalDateUnitTest {
@Test
public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth() {
assertEquals(1, useLocalDate.getFirstDayOfMonth().getDayOfMonth());
assertEquals(1, useLocalDate.getFirstDayOfMonth()
.getDayOfMonth());
}
@Test

View File

@@ -21,7 +21,6 @@ public class FunctionalInterfaceUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(FunctionalInterfaceUnitTest.class);
@Test
public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() {
Map<String, Integer> nameMap = new HashMap<>();
@@ -83,7 +82,8 @@ public class FunctionalInterfaceUnitTest {
return result;
});
List<Integer> fibonacci5 = fibonacci.limit(5).collect(Collectors.toList());
List<Integer> fibonacci5 = fibonacci.limit(5)
.collect(Collectors.toList());
assertEquals(new Integer(1), fibonacci5.get(0));
assertEquals(new Integer(1), fibonacci5.get(1));
@@ -112,7 +112,9 @@ public class FunctionalInterfaceUnitTest {
public void whenUsingPredicateInFilter_thenListValuesAreFilteredOut() {
List<String> names = Arrays.asList("Angela", "Aaron", "Bob", "Claire", "David");
List<String> namesWithA = names.stream().filter(name -> name.startsWith("A")).collect(Collectors.toList());
List<String> namesWithA = names.stream()
.filter(name -> name.startsWith("A"))
.collect(Collectors.toList());
assertEquals(2, namesWithA.size());
assertTrue(namesWithA.contains("Angela"));
@@ -135,7 +137,8 @@ public class FunctionalInterfaceUnitTest {
List<Integer> values = Arrays.asList(3, 5, 8, 9, 12);
int sum = values.stream().reduce(0, (i1, i2) -> i1 + i2);
int sum = values.stream()
.reduce(0, (i1, i2) -> i1 + i2);
assertEquals(37, sum);

View File

@@ -47,7 +47,8 @@ public class ConcurrentMapAggregateStatusManualTest {
executorService.awaitTermination(1, TimeUnit.MINUTES);
for (int i = 1; i <= MAX_SIZE; i++) {
assertEquals("map size should be consistently reliable", i, mapSizes.get(i - 1).intValue());
assertEquals("map size should be consistently reliable", i, mapSizes.get(i - 1)
.intValue());
}
assertEquals(MAX_SIZE, concurrentMap.size());
}
@@ -69,7 +70,8 @@ public class ConcurrentMapAggregateStatusManualTest {
executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.MINUTES);
assertNotEquals("map size collected with concurrent updates not reliable", MAX_SIZE, mapSizes.get(MAX_SIZE - 1).intValue());
assertNotEquals("map size collected with concurrent updates not reliable", MAX_SIZE, mapSizes.get(MAX_SIZE - 1)
.intValue());
assertEquals(MAX_SIZE, concurrentMap.size());
}

View File

@@ -16,8 +16,12 @@ public class ConcurretMapMemoryConsistencyManualTest {
public void givenConcurrentMap_whenSumParallel_thenCorrect() throws Exception {
Map<String, Integer> map = new ConcurrentHashMap<>();
List<Integer> sumList = parallelSum100(map, 1000);
assertEquals(1, sumList.stream().distinct().count());
long wrongResultCount = sumList.stream().filter(num -> num != 100).count();
assertEquals(1, sumList.stream()
.distinct()
.count());
long wrongResultCount = sumList.stream()
.filter(num -> num != 100)
.count();
assertEquals(0, wrongResultCount);
}
@@ -25,8 +29,12 @@ public class ConcurretMapMemoryConsistencyManualTest {
public void givenHashtable_whenSumParallel_thenCorrect() throws Exception {
Map<String, Integer> map = new Hashtable<>();
List<Integer> sumList = parallelSum100(map, 1000);
assertEquals(1, sumList.stream().distinct().count());
long wrongResultCount = sumList.stream().filter(num -> num != 100).count();
assertEquals(1, sumList.stream()
.distinct()
.count());
long wrongResultCount = sumList.stream()
.filter(num -> num != 100)
.count();
assertEquals(0, wrongResultCount);
}
@@ -34,8 +42,12 @@ public class ConcurretMapMemoryConsistencyManualTest {
public void givenHashMap_whenSumParallel_thenError() throws Exception {
Map<String, Integer> map = new HashMap<>();
List<Integer> sumList = parallelSum100(map, 100);
assertNotEquals(1, sumList.stream().distinct().count());
long wrongResultCount = sumList.stream().filter(num -> num != 100).count();
assertNotEquals(1, sumList.stream()
.distinct()
.count());
long wrongResultCount = sumList.stream()
.filter(num -> num != 100)
.count();
assertTrue(wrongResultCount > 0);
}

View File

@@ -13,35 +13,26 @@ import static org.junit.Assert.*;
public class Java8GroupingByCollectorUnitTest {
private static final List<BlogPost> posts = Arrays.asList(
new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15),
new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5),
new BlogPost("Programming guide", "Author 1", BlogPostType.GUIDE, 20),
new BlogPost("News item 2", "Author 2", BlogPostType.NEWS, 35),
new BlogPost("Tech review 2", "Author 1", BlogPostType.REVIEW, 15));
private static final List<BlogPost> posts = Arrays.asList(new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15), new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5),
new BlogPost("Programming guide", "Author 1", BlogPostType.GUIDE, 20), new BlogPost("News item 2", "Author 2", BlogPostType.NEWS, 35), new BlogPost("Tech review 2", "Author 1", BlogPostType.REVIEW, 15));
@Test
public void givenAListOfPosts_whenGroupedByType_thenGetAMapBetweenTypeAndPosts() {
Map<BlogPostType, List<BlogPost>> postsPerType = posts
.stream()
.collect(groupingBy(BlogPost::getType));
Map<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
.collect(groupingBy(BlogPost::getType));
assertEquals(2, postsPerType
.get(BlogPostType.NEWS)
.size());
assertEquals(1, postsPerType
.get(BlogPostType.GUIDE)
.size());
assertEquals(2, postsPerType
.get(BlogPostType.REVIEW)
.size());
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
.size());
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
.size());
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
.size());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeAndTheirTitlesAreJoinedInAString_thenGetAMapBetweenTypeAndCsvTitles() {
Map<BlogPostType, String> postsPerType = posts
.stream()
.collect(groupingBy(BlogPost::getType, mapping(BlogPost::getTitle, joining(", ", "Post titles: [", "]"))));
Map<BlogPostType, String> postsPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, mapping(BlogPost::getTitle, joining(", ", "Post titles: [", "]"))));
assertEquals("Post titles: [News item 1, News item 2]", postsPerType.get(BlogPostType.NEWS));
assertEquals("Post titles: [Programming guide]", postsPerType.get(BlogPostType.GUIDE));
@@ -50,174 +41,135 @@ public class Java8GroupingByCollectorUnitTest {
@Test
public void givenAListOfPosts_whenGroupedByTypeAndSumTheLikes_thenGetAMapBetweenTypeAndPostLikes() {
Map<BlogPostType, Integer> likesPerType = posts
.stream()
.collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes)));
Map<BlogPostType, Integer> likesPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes)));
assertEquals(50, likesPerType
.get(BlogPostType.NEWS)
.intValue());
assertEquals(20, likesPerType
.get(BlogPostType.REVIEW)
.intValue());
assertEquals(20, likesPerType
.get(BlogPostType.GUIDE)
.intValue());
assertEquals(50, likesPerType.get(BlogPostType.NEWS)
.intValue());
assertEquals(20, likesPerType.get(BlogPostType.REVIEW)
.intValue());
assertEquals(20, likesPerType.get(BlogPostType.GUIDE)
.intValue());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeInAnEnumMap_thenGetAnEnumMapBetweenTypeAndPosts() {
EnumMap<BlogPostType, List<BlogPost>> postsPerType = posts
.stream()
.collect(groupingBy(BlogPost::getType, () -> new EnumMap<>(BlogPostType.class), toList()));
EnumMap<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, () -> new EnumMap<>(BlogPostType.class), toList()));
assertEquals(2, postsPerType
.get(BlogPostType.NEWS)
.size());
assertEquals(1, postsPerType
.get(BlogPostType.GUIDE)
.size());
assertEquals(2, postsPerType
.get(BlogPostType.REVIEW)
.size());
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
.size());
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
.size());
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
.size());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeInSets_thenGetAMapBetweenTypesAndSetsOfPosts() {
Map<BlogPostType, Set<BlogPost>> postsPerType = posts
.stream()
.collect(groupingBy(BlogPost::getType, toSet()));
Map<BlogPostType, Set<BlogPost>> postsPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, toSet()));
assertEquals(2, postsPerType
.get(BlogPostType.NEWS)
.size());
assertEquals(1, postsPerType
.get(BlogPostType.GUIDE)
.size());
assertEquals(2, postsPerType
.get(BlogPostType.REVIEW)
.size());
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
.size());
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
.size());
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
.size());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeConcurrently_thenGetAMapBetweenTypeAndPosts() {
ConcurrentMap<BlogPostType, List<BlogPost>> postsPerType = posts
.parallelStream()
.collect(groupingByConcurrent(BlogPost::getType));
ConcurrentMap<BlogPostType, List<BlogPost>> postsPerType = posts.parallelStream()
.collect(groupingByConcurrent(BlogPost::getType));
assertEquals(2, postsPerType
.get(BlogPostType.NEWS)
.size());
assertEquals(1, postsPerType
.get(BlogPostType.GUIDE)
.size());
assertEquals(2, postsPerType
.get(BlogPostType.REVIEW)
.size());
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
.size());
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
.size());
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
.size());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeAndAveragingLikes_thenGetAMapBetweenTypeAndAverageNumberOfLikes() {
Map<BlogPostType, Double> averageLikesPerType = posts
.stream()
.collect(groupingBy(BlogPost::getType, averagingInt(BlogPost::getLikes)));
Map<BlogPostType, Double> averageLikesPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, averagingInt(BlogPost::getLikes)));
assertEquals(25, averageLikesPerType
.get(BlogPostType.NEWS)
.intValue());
assertEquals(20, averageLikesPerType
.get(BlogPostType.GUIDE)
.intValue());
assertEquals(10, averageLikesPerType
.get(BlogPostType.REVIEW)
.intValue());
assertEquals(25, averageLikesPerType.get(BlogPostType.NEWS)
.intValue());
assertEquals(20, averageLikesPerType.get(BlogPostType.GUIDE)
.intValue());
assertEquals(10, averageLikesPerType.get(BlogPostType.REVIEW)
.intValue());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeAndCounted_thenGetAMapBetweenTypeAndNumberOfPosts() {
Map<BlogPostType, Long> numberOfPostsPerType = posts
.stream()
.collect(groupingBy(BlogPost::getType, counting()));
Map<BlogPostType, Long> numberOfPostsPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, counting()));
assertEquals(2, numberOfPostsPerType
.get(BlogPostType.NEWS)
.intValue());
assertEquals(1, numberOfPostsPerType
.get(BlogPostType.GUIDE)
.intValue());
assertEquals(2, numberOfPostsPerType
.get(BlogPostType.REVIEW)
.intValue());
assertEquals(2, numberOfPostsPerType.get(BlogPostType.NEWS)
.intValue());
assertEquals(1, numberOfPostsPerType.get(BlogPostType.GUIDE)
.intValue());
assertEquals(2, numberOfPostsPerType.get(BlogPostType.REVIEW)
.intValue());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeAndMaxingLikes_thenGetAMapBetweenTypeAndMaximumNumberOfLikes() {
Map<BlogPostType, Optional<BlogPost>> maxLikesPerPostType = posts
.stream()
.collect(groupingBy(BlogPost::getType, maxBy(comparingInt(BlogPost::getLikes))));
Map<BlogPostType, Optional<BlogPost>> maxLikesPerPostType = posts.stream()
.collect(groupingBy(BlogPost::getType, maxBy(comparingInt(BlogPost::getLikes))));
assertTrue(maxLikesPerPostType
.get(BlogPostType.NEWS)
.isPresent());
assertEquals(35, maxLikesPerPostType
.get(BlogPostType.NEWS)
.get()
.getLikes());
assertTrue(maxLikesPerPostType.get(BlogPostType.NEWS)
.isPresent());
assertEquals(35, maxLikesPerPostType.get(BlogPostType.NEWS)
.get()
.getLikes());
assertTrue(maxLikesPerPostType
.get(BlogPostType.GUIDE)
.isPresent());
assertEquals(20, maxLikesPerPostType
.get(BlogPostType.GUIDE)
.get()
.getLikes());
assertTrue(maxLikesPerPostType.get(BlogPostType.GUIDE)
.isPresent());
assertEquals(20, maxLikesPerPostType.get(BlogPostType.GUIDE)
.get()
.getLikes());
assertTrue(maxLikesPerPostType
.get(BlogPostType.REVIEW)
.isPresent());
assertEquals(15, maxLikesPerPostType
.get(BlogPostType.REVIEW)
.get()
.getLikes());
assertTrue(maxLikesPerPostType.get(BlogPostType.REVIEW)
.isPresent());
assertEquals(15, maxLikesPerPostType.get(BlogPostType.REVIEW)
.get()
.getLikes());
}
@Test
public void givenAListOfPosts_whenGroupedByAuthorAndThenByType_thenGetAMapBetweenAuthorAndMapsBetweenTypeAndBlogPosts() {
Map<String, Map<BlogPostType, List<BlogPost>>> map = posts
.stream()
.collect(groupingBy(BlogPost::getAuthor, groupingBy(BlogPost::getType)));
Map<String, Map<BlogPostType, List<BlogPost>>> map = posts.stream()
.collect(groupingBy(BlogPost::getAuthor, groupingBy(BlogPost::getType)));
assertEquals(1, map
.get("Author 1")
.get(BlogPostType.NEWS)
.size());
assertEquals(1, map
.get("Author 1")
.get(BlogPostType.GUIDE)
.size());
assertEquals(1, map
.get("Author 1")
.get(BlogPostType.REVIEW)
.size());
assertEquals(1, map.get("Author 1")
.get(BlogPostType.NEWS)
.size());
assertEquals(1, map.get("Author 1")
.get(BlogPostType.GUIDE)
.size());
assertEquals(1, map.get("Author 1")
.get(BlogPostType.REVIEW)
.size());
assertEquals(1, map
.get("Author 2")
.get(BlogPostType.NEWS)
.size());
assertEquals(1, map
.get("Author 2")
.get(BlogPostType.REVIEW)
.size());
assertNull(map
.get("Author 2")
.get(BlogPostType.GUIDE));
assertEquals(1, map.get("Author 2")
.get(BlogPostType.NEWS)
.size());
assertEquals(1, map.get("Author 2")
.get(BlogPostType.REVIEW)
.size());
assertNull(map.get("Author 2")
.get(BlogPostType.GUIDE));
}
@Test
public void givenAListOfPosts_whenGroupedByTypeAndSummarizingLikes_thenGetAMapBetweenTypeAndSummary() {
Map<BlogPostType, IntSummaryStatistics> likeStatisticsPerType = posts
.stream()
.collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes)));
Map<BlogPostType, IntSummaryStatistics> likeStatisticsPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes)));
IntSummaryStatistics newsLikeStatistics = likeStatisticsPerType.get(BlogPostType.NEWS);

View File

@@ -17,8 +17,8 @@ public class Java8MapAndFlatMap {
@Test
public void givenStream_whenCalledMap_thenProduceList() {
List<String> myList = Stream.of("a", "b")
.map(String::toUpperCase)
.collect(Collectors.toList());
.map(String::toUpperCase)
.collect(Collectors.toList());
assertEquals(asList("A", "B"), myList);
}
@@ -27,9 +27,9 @@ public class Java8MapAndFlatMap {
List<List<String>> list = Arrays.asList(Arrays.asList("a"), Arrays.asList("b"));
System.out.println(list);
System.out.println(list
.stream().flatMap(Collection::stream)
.collect(Collectors.toList()));
System.out.println(list.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList()));
}
@Test
@@ -40,13 +40,11 @@ public class Java8MapAndFlatMap {
@Test
public void givenOptional_whenCalledFlatMap_thenProduceFlattenedOptional() {
assertEquals(Optional.of(Optional.of("STRING")), Optional
.of("string")
.map(s -> Optional.of("STRING")));
assertEquals(Optional.of(Optional.of("STRING")), Optional.of("string")
.map(s -> Optional.of("STRING")));
assertEquals(Optional.of("STRING"), Optional
.of("string")
.flatMap(s -> Optional.of("STRING")));
assertEquals(Optional.of("STRING"), Optional.of("string")
.flatMap(s -> Optional.of("STRING")));
}
}

View File

@@ -55,7 +55,12 @@ public class JavaFolderSizeUnitTest {
@Test
public void whenGetFolderSizeUsingJava8_thenCorrect() throws IOException {
final Path folder = Paths.get(path);
final long size = Files.walk(folder).filter(p -> p.toFile().isFile()).mapToLong(p -> p.toFile().length()).sum();
final long size = Files.walk(folder)
.filter(p -> p.toFile()
.isFile())
.mapToLong(p -> p.toFile()
.length())
.sum();
assertEquals(EXPECTED_SIZE, size);
}
@@ -72,8 +77,12 @@ public class JavaFolderSizeUnitTest {
public void whenGetFolderSizeUsingGuava_thenCorrect() {
final File folder = new File(path);
final Iterable<File> files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder);
final long size = StreamSupport.stream(files.spliterator(), false).filter(File::isFile).mapToLong(File::length).sum();
final Iterable<File> files = com.google.common.io.Files.fileTreeTraverser()
.breadthFirstTraversal(folder);
final long size = StreamSupport.stream(files.spliterator(), false)
.filter(File::isFile)
.mapToLong(File::length)
.sum();
assertEquals(EXPECTED_SIZE, size);
}

View File

@@ -1,4 +1,5 @@
package com.baeldung.java8.comparator;
import java.util.Arrays;
import java.util.Comparator;
@@ -25,44 +26,32 @@ public class Java8ComparatorUnitTest {
@Before
public void initData() {
employees = new Employee[] { new Employee("John", 25, 3000, 9922001), new Employee("Ace", 22, 2000, 5924001),
new Employee("Keith", 35, 4000, 3924401) };
employeesArrayWithNulls = new Employee[] { new Employee("John", 25, 3000, 9922001), null, new Employee("Ace", 22, 2000, 5924001),
null, new Employee("Keith", 35, 4000, 3924401) };
employees = new Employee[] { new Employee("John", 25, 3000, 9922001), new Employee("Ace", 22, 2000, 5924001), new Employee("Keith", 35, 4000, 3924401) };
employeesArrayWithNulls = new Employee[] { new Employee("John", 25, 3000, 9922001), null, new Employee("Ace", 22, 2000, 5924001), null, new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByName = new Employee[] { new Employee("Ace", 22, 2000, 5924001),
new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByNameDesc = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("John", 25, 3000, 9922001),
new Employee("Ace", 22, 2000, 5924001) };
sortedEmployeesByName = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByNameDesc = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("John", 25, 3000, 9922001), new Employee("Ace", 22, 2000, 5924001) };
sortedEmployeesByAge = new Employee[] { new Employee("Ace", 22, 2000, 5924001),
new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByAge = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByMobile = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("Ace", 22, 2000, 5924001),
new Employee("John", 25, 3000, 9922001), };
sortedEmployeesByMobile = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), };
sortedEmployeesBySalary = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001),
new Employee("Keith", 35, 4000, 3924401), };
sortedEmployeesBySalary = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401), };
sortedEmployeesArray_WithNullsFirst = new Employee[] { null, null, new Employee("Ace", 22, 2000, 5924001),
new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesArray_WithNullsLast = new Employee[] { new Employee("Ace", 22, 2000, 5924001),
new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401), null, null };
sortedEmployeesArray_WithNullsFirst = new Employee[] { null, null, new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesArray_WithNullsLast = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401), null, null };
someMoreEmployees = new Employee[] { new Employee("Jake", 25, 3000, 9922001), new Employee("Jake", 22, 2000, 5924001),
new Employee("Ace", 22, 3000, 6423001), new Employee("Keith", 35, 4000, 3924401) };
someMoreEmployees = new Employee[] { new Employee("Jake", 25, 3000, 9922001), new Employee("Jake", 22, 2000, 5924001), new Employee("Ace", 22, 3000, 6423001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByAgeName = new Employee[] { new Employee("Ace", 22, 3000, 6423001),
new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByNameAge = new Employee[] { new Employee("Ace", 22, 3000, 6423001),
new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByAgeName = new Employee[] { new Employee("Ace", 22, 3000, 6423001), new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByNameAge = new Employee[] { new Employee("Ace", 22, 3000, 6423001), new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
}
@Test
public void whenComparing_thenSortedByName() {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
Arrays.sort(employees, employeeNameComparator);
// System.out.println(Arrays.toString(employees));
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByName));
}
@@ -72,16 +61,16 @@ public class Java8ComparatorUnitTest {
return s2.compareTo(s1);
});
Arrays.sort(employees, employeeNameComparator);
// System.out.println(Arrays.toString(employees));
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
}
@Test
public void whenReversed_thenSortedByNameDesc() {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
Comparator<Employee> employeeNameComparatorReversed = employeeNameComparator.reversed();
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
Comparator<Employee> employeeNameComparatorReversed = employeeNameComparator.reversed();
Arrays.sort(employees, employeeNameComparatorReversed);
// System.out.println(Arrays.toString(employees));
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
}
@@ -89,7 +78,7 @@ public class Java8ComparatorUnitTest {
public void whenComparingInt_thenSortedByAge() {
Comparator<Employee> employeeAgeComparator = Comparator.comparingInt(Employee::getAge);
Arrays.sort(employees, employeeAgeComparator);
// System.out.println(Arrays.toString(employees));
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByAge));
}
@@ -97,7 +86,7 @@ public class Java8ComparatorUnitTest {
public void whenComparingLong_thenSortedByMobile() {
Comparator<Employee> employeeMobileComparator = Comparator.comparingLong(Employee::getMobile);
Arrays.sort(employees, employeeMobileComparator);
// System.out.println(Arrays.toString(employees));
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByMobile));
}
@@ -105,7 +94,7 @@ public class Java8ComparatorUnitTest {
public void whenComparingDouble_thenSortedBySalary() {
Comparator<Employee> employeeSalaryComparator = Comparator.comparingDouble(Employee::getSalary);
Arrays.sort(employees, employeeSalaryComparator);
// System.out.println(Arrays.toString(employees));
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesBySalary));
}
@@ -113,7 +102,7 @@ public class Java8ComparatorUnitTest {
public void whenNaturalOrder_thenSortedByName() {
Comparator<Employee> employeeNameComparator = Comparator.<Employee> naturalOrder();
Arrays.sort(employees, employeeNameComparator);
// System.out.println(Arrays.toString(employees));
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByName));
}
@@ -121,7 +110,7 @@ public class Java8ComparatorUnitTest {
public void whenReverseOrder_thenSortedByNameDesc() {
Comparator<Employee> employeeNameComparator = Comparator.<Employee> reverseOrder();
Arrays.sort(employees, employeeNameComparator);
// System.out.println(Arrays.toString(employees));
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
}
@@ -130,7 +119,7 @@ public class Java8ComparatorUnitTest {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
Comparator<Employee> employeeNameComparator_nullFirst = Comparator.nullsFirst(employeeNameComparator);
Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullFirst);
// System.out.println(Arrays.toString(employeesArrayWithNulls));
// System.out.println(Arrays.toString(employeesArrayWithNulls));
assertTrue(Arrays.equals(employeesArrayWithNulls, sortedEmployeesArray_WithNullsFirst));
}
@@ -139,27 +128,28 @@ public class Java8ComparatorUnitTest {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
Comparator<Employee> employeeNameComparator_nullLast = Comparator.nullsLast(employeeNameComparator);
Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullLast);
// System.out.println(Arrays.toString(employeesArrayWithNulls));
// System.out.println(Arrays.toString(employeesArrayWithNulls));
assertTrue(Arrays.equals(employeesArrayWithNulls, sortedEmployeesArray_WithNullsLast));
}
@Test
public void whenThenComparing_thenSortedByAgeName() {
Comparator<Employee> employee_Age_Name_Comparator = Comparator.comparing(Employee::getAge).thenComparing(Employee::getName);
Comparator<Employee> employee_Age_Name_Comparator = Comparator.comparing(Employee::getAge)
.thenComparing(Employee::getName);
Arrays.sort(someMoreEmployees, employee_Age_Name_Comparator);
// System.out.println(Arrays.toString(someMoreEmployees));
// System.out.println(Arrays.toString(someMoreEmployees));
assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByAgeName));
}
@Test
public void whenThenComparing_thenSortedByNameAge() {
Comparator<Employee> employee_Name_Age_Comparator = Comparator.comparing(Employee::getName).thenComparingInt(Employee::getAge);
Comparator<Employee> employee_Name_Age_Comparator = Comparator.comparing(Employee::getName)
.thenComparingInt(Employee::getAge);
Arrays.sort(someMoreEmployees, employee_Name_Age_Comparator);
// System.out.println(Arrays.toString(someMoreEmployees));
// System.out.println(Arrays.toString(someMoreEmployees));
assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByNameAge));
}
}

View File

@@ -17,7 +17,6 @@ public class OptionalUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(OptionalUnitTest.class);
// creating Optional
@Test
public void whenCreatesEmptyOptional_thenCorrect() {
@@ -94,9 +93,11 @@ public class OptionalUnitTest {
public void whenOptionalFilterWorks_thenCorrect() {
Integer year = 2016;
Optional<Integer> yearOptional = Optional.of(year);
boolean is2016 = yearOptional.filter(y -> y == 2016).isPresent();
boolean is2016 = yearOptional.filter(y -> y == 2016)
.isPresent();
assertTrue(is2016);
boolean is2017 = yearOptional.filter(y -> y == 2017).isPresent();
boolean is2017 = yearOptional.filter(y -> y == 2017)
.isPresent();
assertFalse(is2017);
}
@@ -128,7 +129,11 @@ public class OptionalUnitTest {
}
public boolean priceIsInRange2(Modem modem2) {
return Optional.ofNullable(modem2).map(Modem::getPrice).filter(p -> p >= 10).filter(p -> p <= 15).isPresent();
return Optional.ofNullable(modem2)
.map(Modem::getPrice)
.filter(p -> p >= 10)
.filter(p -> p <= 15)
.isPresent();
}
// Transforming Value With map()
@@ -137,7 +142,8 @@ public class OptionalUnitTest {
List<String> companyNames = Arrays.asList("paypal", "oracle", "", "microsoft", "", "apple");
Optional<List<String>> listOptional = Optional.of(companyNames);
int size = listOptional.map(List::size).orElse(0);
int size = listOptional.map(List::size)
.orElse(0);
assertEquals(6, size);
}
@@ -146,7 +152,8 @@ public class OptionalUnitTest {
String name = "baeldung";
Optional<String> nameOptional = Optional.of(name);
int len = nameOptional.map(String::length).orElse(0);
int len = nameOptional.map(String::length)
.orElse(0);
assertEquals(8, len);
}
@@ -154,10 +161,13 @@ public class OptionalUnitTest {
public void givenOptional_whenMapWorksWithFilter_thenCorrect() {
String password = " password ";
Optional<String> passOpt = Optional.of(password);
boolean correctPassword = passOpt.filter(pass -> pass.equals("password")).isPresent();
boolean correctPassword = passOpt.filter(pass -> pass.equals("password"))
.isPresent();
assertFalse(correctPassword);
correctPassword = passOpt.map(String::trim).filter(pass -> pass.equals("password")).isPresent();
correctPassword = passOpt.map(String::trim)
.filter(pass -> pass.equals("password"))
.isPresent();
assertTrue(correctPassword);
}
@@ -172,7 +182,8 @@ public class OptionalUnitTest {
String name1 = nameOptional.orElseThrow(IllegalArgumentException::new);
assertEquals("john", name1);
String name = personOptional.flatMap(Person::getName).orElseThrow(IllegalArgumentException::new);
String name = personOptional.flatMap(Person::getName)
.orElseThrow(IllegalArgumentException::new);
assertEquals("john", name);
}
@@ -182,7 +193,9 @@ public class OptionalUnitTest {
person.setPassword("password");
Optional<Person> personOptional = Optional.of(person);
String password = personOptional.flatMap(Person::getPassword).filter(cleanPass -> cleanPass.equals("password")).orElseThrow(IllegalArgumentException::new);
String password = personOptional.flatMap(Person::getPassword)
.filter(cleanPass -> cleanPass.equals("password"))
.orElseThrow(IllegalArgumentException::new);
assertEquals("password", password);
}
@@ -190,7 +203,8 @@ public class OptionalUnitTest {
@Test
public void whenOrElseWorks_thenCorrect() {
String nullName = null;
String name = Optional.ofNullable(nullName).orElse("john");
String name = Optional.ofNullable(nullName)
.orElse("john");
assertEquals("john", name);
}
@@ -198,7 +212,8 @@ public class OptionalUnitTest {
@Test
public void whenOrElseGetWorks_thenCorrect() {
String nullName = null;
String name = Optional.ofNullable(nullName).orElseGet(() -> "john");
String name = Optional.ofNullable(nullName)
.orElseGet(() -> "john");
assertEquals("john", name);
}
@@ -207,11 +222,13 @@ public class OptionalUnitTest {
public void whenOrElseGetAndOrElseOverlap_thenCorrect() {
String text = null;
LOG.debug("Using orElseGet:");
String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault);
String defaultText = Optional.ofNullable(text)
.orElseGet(this::getMyDefault);
assertEquals("Default Value", defaultText);
LOG.debug("Using orElse:");
defaultText = Optional.ofNullable(text).orElse(getMyDefault());
defaultText = Optional.ofNullable(text)
.orElse(getMyDefault());
assertEquals("Default Value", defaultText);
}
@@ -219,11 +236,13 @@ public class OptionalUnitTest {
public void whenOrElseGetAndOrElseDiffer_thenCorrect() {
String text = "Text present";
LOG.debug("Using orElseGet:");
String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault);
String defaultText = Optional.ofNullable(text)
.orElseGet(this::getMyDefault);
assertEquals("Text present", defaultText);
LOG.debug("Using orElse:");
defaultText = Optional.ofNullable(text).orElse(getMyDefault());
defaultText = Optional.ofNullable(text)
.orElse(getMyDefault());
assertEquals("Text present", defaultText);
}
@@ -231,7 +250,8 @@ public class OptionalUnitTest {
@Test(expected = IllegalArgumentException.class)
public void whenOrElseThrowWorks_thenCorrect() {
String nullName = null;
String name = Optional.ofNullable(nullName).orElseThrow(IllegalArgumentException::new);
String name = Optional.ofNullable(nullName)
.orElseThrow(IllegalArgumentException::new);
}
public String getMyDefault() {

View File

@@ -43,6 +43,8 @@ public class FlattenNestedListUnitTest {
}
private <T> List<T> flattenListOfListsStream(List<List<T>> list) {
return list.stream().flatMap(Collection::stream).collect(Collectors.toList());
return list.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
}

View File

@@ -15,56 +15,56 @@ public class RoundTest {
private double expected = 2.03d;
@Test
public void givenDecimalNumber_whenRoundToNDecimalPlaces_thenGetExpectedResult() {
public void givenDecimalNumber_whenRoundToNDecimalPlaces_thenGetExpectedResult() {
Assert.assertEquals(expected, Round.round(value, places), delta);
Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta);
Assert.assertEquals(expected, Round.roundAvoid(value, places), delta);
Assert.assertEquals(expected, Precision.round(value, places), delta);
Assert.assertEquals(expected, DoubleRounder.round(value, places), delta);
places = 3;
expected = 2.035d;
Assert.assertEquals(expected, Round.round(value, places), delta);
Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta);
Assert.assertEquals(expected, Round.roundAvoid(value, places), delta);
Assert.assertEquals(expected, Precision.round(value, places), delta);
Assert.assertEquals(expected, DoubleRounder.round(value, places), delta);
value = 1000.0d;
places = 17;
expected = 1000.0d;
Assert.assertEquals(expected, Round.round(value, places), delta);
Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta);
Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 92.23372036854776 !
Assert.assertEquals(expected, Precision.round(value, places), delta);
Assert.assertEquals(expected, DoubleRounder.round(value, places), delta);
value = 256.025d;
places = 2;
expected = 256.03d;
Assert.assertEquals(expected, Round.round(value, places), delta);
Assert.assertNotEquals(expected, Round.roundNotPrecise(value, places), delta); // Returns: 256.02 !
Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 256.02 !
Assert.assertEquals(expected, Precision.round(value, places), delta);
Assert.assertNotEquals(expected, DoubleRounder.round(value, places), delta); // Returns: 256.02 !
value = 260.775d;
value = 260.775d;
places = 2;
expected = 260.78d;
Assert.assertEquals(expected, Round.round(value, places), delta);
Assert.assertNotEquals(expected, Round.roundNotPrecise(value, places), delta); // Returns: 260.77 !
Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 260.77 !
Assert.assertEquals(expected, Precision.round(value, places), delta);
Assert.assertNotEquals(expected, DoubleRounder.round(value, places), delta); // Returns: 260.77 !
value = 90080070060.1d;
places = 9;
expected = 90080070060.1d;
Assert.assertEquals(expected, Round.round(value, places), delta);
Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta);
Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 9.223372036854776E9 !

View File

@@ -14,7 +14,8 @@ public class EchoIntegrationTest {
@BeforeClass
public static void start() throws InterruptedException {
Executors.newSingleThreadExecutor().submit(() -> new EchoServer().start(PORT));
Executors.newSingleThreadExecutor()
.submit(() -> new EchoServer().start(PORT));
Thread.sleep(500);
}

View File

@@ -17,7 +17,8 @@ public class GreetServerIntegrationTest {
@BeforeClass
public static void start() throws InterruptedException {
Executors.newSingleThreadExecutor().submit(() -> new GreetServer().start(PORT));
Executors.newSingleThreadExecutor()
.submit(() -> new GreetServer().start(PORT));
Thread.sleep(500);
}

View File

@@ -96,9 +96,12 @@ public class JavaIoUnitTest {
// utils
private final void logMemory() {
logger.info("Max Memory: {} Mb", Runtime.getRuntime().maxMemory() / 1048576);
logger.info("Total Memory: {} Mb", Runtime.getRuntime().totalMemory() / 1048576);
logger.info("Free Memory: {} Mb", Runtime.getRuntime().freeMemory() / 1048576);
logger.info("Max Memory: {} Mb", Runtime.getRuntime()
.maxMemory() / 1048576);
logger.info("Total Memory: {} Mb", Runtime.getRuntime()
.totalMemory() / 1048576);
logger.info("Free Memory: {} Mb", Runtime.getRuntime()
.freeMemory() / 1048576);
}
}

View File

@@ -13,7 +13,6 @@ public class JavaRandomUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(JavaRandomUnitTest.class);
// tests - random long
@Test
@@ -25,7 +24,8 @@ public class JavaRandomUnitTest {
@Test
public void givenUsingApacheCommons_whenGeneratingRandomLongUnbounded_thenCorrect() {
final long generatedLong = new RandomDataGenerator().getRandomGenerator().nextLong();
final long generatedLong = new RandomDataGenerator().getRandomGenerator()
.nextLong();
LOG.debug("{}", generatedLong);
}
@@ -68,7 +68,8 @@ public class JavaRandomUnitTest {
@Test
public void givenUsingApache_whenGeneratingRandomIntegerUnbounded_thenCorrect() {
final Integer generatedInteger = new RandomDataGenerator().getRandomGenerator().nextInt();
final Integer generatedInteger = new RandomDataGenerator().getRandomGenerator()
.nextInt();
LOG.debug("{}", generatedInteger);
}
@@ -93,7 +94,8 @@ public class JavaRandomUnitTest {
@Test
public void givenUsingApache_whenGeneratingRandomFloatUnbounded_thenCorrect() {
final float generatedFloat = new RandomDataGenerator().getRandomGenerator().nextFloat();
final float generatedFloat = new RandomDataGenerator().getRandomGenerator()
.nextFloat();
LOG.debug("{}", generatedFloat);
}
@@ -111,7 +113,8 @@ public class JavaRandomUnitTest {
public void givenUsingApache_whenGeneratingRandomFloatBounded_thenCorrect() {
final float leftLimit = 1F;
final float rightLimit = 10F;
final float randomFloat = new RandomDataGenerator().getRandomGenerator().nextFloat();
final float randomFloat = new RandomDataGenerator().getRandomGenerator()
.nextFloat();
final float generatedFloat = leftLimit + randomFloat * (rightLimit - leftLimit);
LOG.debug("{}", generatedFloat);
@@ -128,7 +131,8 @@ public class JavaRandomUnitTest {
@Test
public void givenUsingApache_whenGeneratingRandomDoubleUnbounded_thenCorrect() {
final double generatedDouble = new RandomDataGenerator().getRandomGenerator().nextDouble();
final double generatedDouble = new RandomDataGenerator().getRandomGenerator()
.nextDouble();
LOG.debug("{}", generatedDouble);
}

View File

@@ -15,7 +15,6 @@ public class JavaTimerLongRunningUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(JavaTimerLongRunningUnitTest.class);
// tests
@Test
@@ -23,7 +22,8 @@ public class JavaTimerLongRunningUnitTest {
final TimerTask timerTask = new TimerTask() {
@Override
public void run() {
LOG.debug("Task performed on: " + new Date() + "\n" + "Thread's name: " + Thread.currentThread().getName());
LOG.debug("Task performed on: " + new Date() + "\n" + "Thread's name: " + Thread.currentThread()
.getName());
}
};
final Timer timer = new Timer("Timer");

View File

@@ -38,7 +38,8 @@ public class Employee implements Comparable {
@Override
public boolean equals(Object obj) {
return ((Employee) obj).getName().equals(getName());
return ((Employee) obj).getName()
.equals(getName());
}
@Override
@@ -49,7 +50,13 @@ public class Employee implements Comparable {
@Override
public String toString() {
return new StringBuffer().append("(").append(getName()).append(getAge()).append(",").append(getSalary()).append(")").toString();
return new StringBuffer().append("(")
.append(getName())
.append(getAge())
.append(",")
.append(getSalary())
.append(")")
.toString();
}
}

View File

@@ -113,7 +113,8 @@ public class JavaSortingUnitTest {
sortedMap.put(entry.getKey(), entry.getValue());
}
assertTrue(Arrays.equals(sortedMap.keySet().toArray(), sortedKeys));
assertTrue(Arrays.equals(sortedMap.keySet()
.toArray(), sortedKeys));
}
@Test
@@ -127,7 +128,8 @@ public class JavaSortingUnitTest {
sortedMap.put(entry.getKey(), entry.getValue());
}
assertTrue(Arrays.equals(sortedMap.values().toArray(), sortedValues));
assertTrue(Arrays.equals(sortedMap.values()
.toArray(), sortedValues));
}
@Test