Last active
August 29, 2015 14:01
-
-
Save mgandin/c36ac02aa04da0562c08 to your computer and use it in GitHub Desktop.
Some small examples in Java 8 with new java.time API, Stream, Lambdas, CompletableFuture, String Joiner, ParallelPrefix & ParallelSetAll in Arrays, File & Path Closeable Stream, List.sort and Map.compute & merge
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package fr.mga.spike; | |
import java.util.concurrent.*; | |
public class ConcurrentFooBar { | |
public static String fooBar(int anInteger) { | |
String result = ""; | |
if (anInteger % 3 == 0) | |
result += "foo"; | |
if (anInteger % 5 == 0) | |
result += "bar"; | |
String integer = String.valueOf(anInteger); | |
for (int i = 0; i < integer.length(); i++) { | |
if (integer.charAt(i) == '3') | |
result += "foo"; | |
if (integer.charAt(i) == '5') | |
result += "bar"; | |
} | |
return result.equals("") ? integer : result; | |
} | |
public static void main(String[] args) throws Exception { | |
ExecutorService executor = Executors.newSingleThreadExecutor(); | |
for (int i = 1; i <= 100; i++) { | |
final int tooFooBar = i; | |
CompletableFuture.supplyAsync( | |
() -> { | |
return fooBar(tooFooBar); | |
}, | |
executor | |
) | |
.thenApply((f) -> f.toUpperCase()) | |
.thenAccept(System.out::println); | |
} | |
executor.shutdown(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package fr.mga.spike; | |
import org.fest.assertions.api.Assertions; | |
import org.junit.Test; | |
import java.time.*; | |
public class DateTest { | |
@Test | |
public void should_calculate_my_age() { | |
LocalDate birthDate = LocalDate.of(1977, Month.JULY,15); | |
LocalDate now = LocalDate.now(); | |
Period age = birthDate.until(now); | |
Assertions.assertThat(age.getYears()).isEqualTo(36); | |
} | |
@Test | |
public void should_compare_two_instants() throws Exception { | |
Instant start = Instant.now(); | |
Instant fortyTwoSecondsLater = start.plus(Duration.ofSeconds(42)); | |
Assertions.assertThat(fortyTwoSecondsLater.isAfter(start)).isTrue(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package fr.mga.spike; | |
import org.fest.assertions.api.Assertions; | |
import org.junit.Test; | |
import java.io.IOException; | |
import java.nio.charset.Charset; | |
import java.nio.file.Files; | |
import java.nio.file.Path; | |
import java.nio.file.Paths; | |
import java.util.List; | |
import java.util.stream.Collectors; | |
import java.util.stream.Stream; | |
public class FileTest { | |
@Test | |
public void should_read_content_of_a_directory() throws IOException { | |
Path path = Paths.get("d:/tmp"); | |
try (Stream<Path> stream = Files.list(path)) { | |
List<String> logSpring = stream.filter(p -> p.getFileName().toString().equals("spring.log")) | |
.map(p -> p.toString()) | |
.collect(Collectors.toList()); | |
Assertions.assertThat(logSpring).hasSize(1); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
@Test | |
public void should_read_content_of_a_file() { | |
Path path = Paths.get("d:/tmp/spring.log"); | |
try (Stream<String> stream = Files.lines(path,Charset.forName("UTF-8"))) { | |
String fileContent = stream.collect(Collectors.joining("\n")); | |
Assertions.assertThat(fileContent).isEqualTo("Hello World !\n" + | |
"this is spring.log content"); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package fr.mga.spike; | |
import org.fest.assertions.api.Assertions; | |
import org.junit.Test; | |
public class LambdaTest { | |
interface User { | |
String computeMail(String firstName,String lastName); | |
} | |
@Test | |
public void should_run_a_simple_lambda() { | |
User user = (firstName,lastName) -> { | |
return firstName + "." + lastName +"@gmail.com"; | |
}; | |
Assertions.assertThat(user.computeMail("mathieu","gandin")).isEqualTo("mathieu.gandin@gmail.com"); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package fr.mga.spike; | |
import org.fest.assertions.api.Assertions; | |
import org.junit.Assert; | |
import org.junit.Test; | |
import java.util.*; | |
public class ListTest { | |
@Test | |
public void should_uppercase_list_string() { | |
List<String> toUpperCase = Arrays.asList("toto", "titi"); | |
toUpperCase.replaceAll(String::toUpperCase); | |
Assertions.assertThat(toUpperCase.get(0)).isEqualTo("TOTO"); | |
Assertions.assertThat(toUpperCase.get(1)).isEqualTo("TITI"); | |
} | |
@Test | |
public void should_sort_by_natural_order() { | |
List<String> list = Arrays.asList("one", "two", "three", "four"); | |
Collections.sort(list,Comparator.naturalOrder()); | |
Assertions.assertThat(list).isEqualTo(Arrays.asList("four", "one", "three", "two")); | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package fr.mga.spike; | |
import org.fest.assertions.api.Assertions; | |
import org.junit.Test; | |
import java.util.concurrent.atomic.LongAccumulator; | |
import java.util.concurrent.atomic.LongAdder; | |
public class LongThreadTest { | |
@Test | |
public void should_add_long_with_thread_safe_code(){ | |
LongAdder adder = new LongAdder(); | |
Runnable thread1 = () -> adder.increment(); | |
Runnable thread2 = () -> { | |
try { | |
Thread.sleep(2000); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
adder.add(40); | |
}; | |
Runnable thread3 = () -> adder.increment(); | |
thread1.run(); | |
thread2.run(); | |
thread3.run(); | |
Assertions.assertThat(adder.sum()).isEqualTo(42); | |
} | |
@Test | |
public void should_accumulate_with_thread_safe_code() { | |
LongAccumulator accumulator = new LongAccumulator((l1,l2) -> l1 + l2,0L); | |
Runnable thread1 = () -> accumulator.accumulate(20); | |
Runnable thread2 = () -> { | |
try { | |
Thread.sleep(2000); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
accumulator.accumulate(20); | |
}; | |
Runnable thread3 = () -> accumulator.accumulate(2); | |
thread1.run(); | |
thread2.run(); | |
thread3.run(); | |
Assertions.assertThat(accumulator.longValue()).isEqualTo(42); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package fr.mga.spike; | |
import org.junit.Assert; | |
import org.junit.Test; | |
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.List; | |
import java.util.stream.Collectors; | |
public class MapReduceTest { | |
@Test | |
public void should_map_reduce_to_numbers() { | |
List<Integer> maList = new ArrayList<>(); | |
for (int i = 1; i <= 1000; i++) { | |
maList.add(i); | |
} | |
int bill = maList.stream() | |
.map(n -> n*n) | |
.filter(n -> n > 100) | |
.limit(3) | |
.reduce((sum,nextElement) -> sum + nextElement) | |
.get(); | |
Assert.assertEquals(434,bill); | |
bill = maList.stream() | |
.mapToInt(Integer::intValue) | |
.map(n -> n*n) | |
.filter(n -> n > 100) | |
.limit(3) | |
.sum(); | |
Assert.assertEquals(434,bill); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package fr.mga.spike; | |
import org.fest.assertions.api.Assertions; | |
import org.junit.Test; | |
import java.util.*; | |
public class MapTest { | |
@Test | |
public void should_merge_two_map() { | |
Map<Integer,List<String>> ageAndPeopleOrga = new HashMap<>(); | |
List<String> peopeWithAgeOf36 = new ArrayList<>(); | |
peopeWithAgeOf36.add("Mathieu"); | |
List<String> peopleWithAgeOf42 = new ArrayList<>(); | |
peopleWithAgeOf42.add("Pierre"); | |
ageAndPeopleOrga.put(36, peopeWithAgeOf36); | |
ageAndPeopleOrga.put(42, peopleWithAgeOf42); | |
ageAndPeopleOrga.merge( | |
42, | |
Arrays.asList("Paul"), | |
(value, valueToAdd) -> { | |
value.addAll(valueToAdd); | |
return value; | |
} | |
); | |
System.out.println(ageAndPeopleOrga); | |
Assertions.assertThat(ageAndPeopleOrga).containsValue(Arrays.asList("Mathieu")); | |
Assertions.assertThat(ageAndPeopleOrga).containsValue(Arrays.asList("Pierre", "Paul")); | |
} | |
@Test | |
public void should_compute_map() { | |
Map<Integer,String> ageAndPeopleOrga = new HashMap<>(); | |
ageAndPeopleOrga.put(36, "Mathieu"); | |
ageAndPeopleOrga.put(42, "Pierre"); | |
ageAndPeopleOrga.put(46, "Paul"); | |
for (Integer key : ageAndPeopleOrga.keySet()) { | |
ageAndPeopleOrga.compute( | |
key, | |
(age, name) -> name + " has " + age + " year" | |
); | |
} | |
System.out.println(ageAndPeopleOrga); | |
Assertions.assertThat(ageAndPeopleOrga).containsValue("Mathieu has 36 year"); | |
Assertions.assertThat(ageAndPeopleOrga).containsValue("Pierre has 42 year"); | |
Assertions.assertThat(ageAndPeopleOrga).containsValue("Paul has 46 year"); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package fr.mga.spike; | |
import org.fest.assertions.api.Assertions; | |
import org.junit.Test; | |
import java.util.Arrays; | |
public class ParallelArraysTest { | |
@Test | |
public void should_right_fold_an_array() { | |
long[] array = new long[]{1,2,3,4}; | |
// Parallel | |
Arrays.parallelPrefix(array, (l1, l2) -> l1 + l2); | |
Assertions.assertThat(array).isEqualTo(new long[]{1,3,6,10}); | |
} | |
@Test | |
public void should_populate_an_array() { | |
long[] array = new long[4]; | |
// Parallel, i is the index | |
Arrays.parallelSetAll(array,(index -> index + 1 )); | |
Assertions.assertThat(array).isEqualTo(new long[]{1,2,3,4}); | |
} | |
@Test | |
public void should_sort() { | |
long[] array = new long[]{4,3,2,1}; | |
// Parallel | |
Arrays.parallelSort(array); | |
Assertions.assertThat(array).isEqualTo(new long[]{1,2,3,4}); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package fr.mga.spike; | |
import org.fest.assertions.api.Assertions; | |
import org.junit.Test; | |
import java.util.stream.Collectors; | |
public class StringTest { | |
@Test | |
public void should_get_hello_chars_from_hello_world_string() { | |
String message = "hello world !"; | |
String hello = message.chars() | |
.limit(5) | |
.mapToObj(c -> String.valueOf((char)c)) | |
.collect(Collectors.joining()); | |
Assertions.assertThat(hello).isEqualTo("hello"); | |
} | |
@Test | |
public void should_join() { | |
String hello = "hello"; | |
String world = "world"; | |
String helloWorld = String.join(" ",hello,world,"!"); | |
Assertions.assertThat(helloWorld).isEqualTo("hello world !"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment