[BAEL-18364] move spring-rest-*** articles - 1

This commit is contained in:
Sjmillington
2019-10-17 17:17:31 +01:00
parent db85c8f275
commit f1673ce653
20415 changed files with 1639515 additions and 0 deletions
@@ -0,0 +1,13 @@
package com.baeldung.java_8_features;
import java.util.Arrays;
import java.util.List;
public class Detail {
private static final List<String> PARTS = Arrays.asList("turbine", "pump");
public List<String> getParts() {
return PARTS;
}
}
@@ -0,0 +1,70 @@
package com.baeldung.reduce.application;
import com.baeldung.reduce.entities.User;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Warmup;
public class Application {
public static void main(String[] args) throws Exception {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
int result1 = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element);
System.out.println(result1);
int result2 = numbers.stream().reduce(0, Integer::sum);
System.out.println(result2);
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
String result3 = letters.stream().reduce("", (partialString, element) -> partialString + element);
System.out.println(result3);
String result4 = letters.stream().reduce("", String::concat);
System.out.println(result4);
String result5 = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase());
System.out.println(result5);
List<User> users = Arrays.asList(new User("John", 30), new User("Julie", 35));
int result6 = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
System.out.println(result6);
String result7 = letters.parallelStream().reduce("", String::concat);
System.out.println(result7);
int result8 = users.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
System.out.println(result8);
org.openjdk.jmh.Main.main(args);
}
@Benchmark
@Fork(value = 1, warmups = 2)
@Warmup(iterations = 2)
@BenchmarkMode(Mode.AverageTime)
public void executeReduceOnParallelizedStream() {
List<User> userList = new ArrayList<>();
for (int i = 0; i <= 1000000; i++) {
userList.add(new User("John" + i, i));
}
userList.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
}
@Benchmark
@Fork(value = 1, warmups = 2)
@Warmup(iterations = 2)
@BenchmarkMode(Mode.AverageTime)
public void executeReduceOnSequentialStream() {
List<User> userList = new ArrayList<>();
for (int i = 0; i <= 1000000; i++) {
userList.add(new User("John" + i, i));
}
userList.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
}
}
@@ -0,0 +1,25 @@
package com.baeldung.reduce.entities;
public class User {
private final String name;
private final int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "User{" + "name=" + name + ", age=" + age + '}';
}
}
@@ -0,0 +1,52 @@
package com.baeldung.reduce.utilities;
import java.util.List;
import java.util.function.BiFunction;
import java.util.logging.Level;
import java.util.logging.Logger;
public abstract class NumberUtils {
private static final Logger LOGGER = Logger.getLogger(NumberUtils.class.getName());
public static int divideListElements(List<Integer> values, Integer divider) {
return values.stream()
.reduce(0, (a, b) -> {
try {
return a / divider + b / divider;
} catch (ArithmeticException e) {
LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero");
}
return 0;
});
}
public static int divideListElementsWithExtractedTryCatchBlock(List<Integer> values, int divider) {
return values.stream().reduce(0, (a, b) -> divide(a, divider) + divide(b, divider));
}
public static int divideListElementsWithApplyFunctionMethod(List<Integer> values, int divider) {
BiFunction<Integer, Integer, Integer> division = (a, b) -> a / b;
return values.stream().reduce(0, (a, b) -> applyFunction(division, a, divider) + applyFunction(division, b, divider));
}
private static int divide(int value, int factor) {
int result = 0;
try {
result = value / factor;
} catch (ArithmeticException e) {
LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero");
}
return result;
}
private static int applyFunction(BiFunction<Integer, Integer, Integer> function, int a, int b) {
try {
return function.apply(a, b);
}
catch(Exception e) {
LOGGER.log(Level.INFO, "Exception occurred!");
}
return 0;
}
}
@@ -0,0 +1,32 @@
package com.baeldung.stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.stream.Stream;
public class InfiniteStreams {
private static final Logger LOG = LoggerFactory.getLogger(InfiniteStreams.class);
public static void main(String[] args) {
doWhileOldWay();
doWhileStreamWay();
}
private static void doWhileOldWay() {
int i = 0;
while (i < 10) {
LOG.debug("{}", i);
i++;
}
}
private static void doWhileStreamWay() {
Stream<Integer> integers = Stream.iterate(0, i -> i + 1);
integers.limit(10).forEach(System.out::println);
}
}
@@ -0,0 +1,23 @@
package com.baeldung.stream;
import java.util.Arrays;
import java.util.stream.IntStream;
class PrimitiveStreams {
int min(int[] integers) {
return Arrays.stream(integers).min().getAsInt();
}
int max(int... integers) {
return IntStream.of(integers).max().getAsInt();
}
int sum(int... integers) {
return IntStream.of(integers).sum();
}
double avg(int... integers) {
return IntStream.of(integers).average().getAsDouble();
}
}
@@ -0,0 +1,48 @@
package com.baeldung.stream;
import java.util.List;
import java.util.stream.Stream;
/**
* Created by Alex Vengr
*/
public class Product {
private int price;
private String name;
private boolean utilize;
public Product(int price, String name) {
this(price);
this.name = name;
}
public Product(int price) {
this.price = price;
}
public Product() {
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static Stream<String> streamOf(List<String> list) {
return (list == null || list.isEmpty()) ? Stream.empty() : list.stream();
}
}
@@ -0,0 +1,24 @@
package com.baeldung.stream;
import java.util.List;
import java.util.stream.Stream;
public class StreamApi {
public static String getLastElementUsingReduce(List<String> valueList) {
Stream<String> stream = valueList.stream();
return stream.reduce((first, second) -> second).orElse(null);
}
public static Integer getInfiniteStreamLastElementUsingReduce() {
Stream<Integer> stream = Stream.iterate(0, i -> i + 1);
return stream.limit(20).reduce((first, second) -> second).orElse(null);
}
public static String getLastElementUsingSkip(List<String> valueList) {
long count = (long) valueList.size();
Stream<String> stream = valueList.stream();
return stream.skip(count - 1).findFirst().orElse(null);
}
}
@@ -0,0 +1,62 @@
package com.baeldung.stream;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import com.codepoetics.protonpack.Indexed;
import com.codepoetics.protonpack.StreamUtils;
import io.vavr.collection.Stream;
import one.util.streamex.EntryStream;
public class StreamIndices {
public static List<String> getEvenIndexedStrings(String[] names) {
List<String> evenIndexedNames = IntStream.range(0, names.length)
.filter(i -> i % 2 == 0)
.mapToObj(i -> names[i])
.collect(Collectors.toList());
return evenIndexedNames;
}
public List<String> getEvenIndexedStringsVersionTwo(List<String> names) {
List<String> evenIndexedNames = EntryStream.of(names)
.filterKeyValue((index, name) -> index % 2 == 0)
.values()
.toList();
return evenIndexedNames;
}
public static List<Indexed<String>> getEvenIndexedStrings(List<String> names) {
List<Indexed<String>> list = StreamUtils.zipWithIndex(names.stream())
.filter(i -> i.getIndex() % 2 == 0)
.collect(Collectors.toList());
return list;
}
public static List<Indexed<String>> getOddIndexedStrings(List<String> names) {
List<Indexed<String>> list = StreamUtils.zipWithIndex(names.stream())
.filter(i -> i.getIndex() % 2 == 1)
.collect(Collectors.toList());
return list;
}
public static List<String> getOddIndexedStrings(String[] names) {
List<String> oddIndexedNames = IntStream.range(0, names.length)
.filter(i -> i % 2 == 1)
.mapToObj(i -> names[i])
.collect(Collectors.toList());
return oddIndexedNames;
}
public static List<String> getOddIndexedStringsVersionTwo(String[] names) {
List<String> oddIndexedNames = Stream.of(names)
.zipWithIndex()
.filter(tuple -> tuple._2 % 2 == 1)
.map(tuple -> tuple._1)
.toJavaList();
return oddIndexedNames;
}
}
@@ -0,0 +1,55 @@
package com.baeldung.stream.filter;
import javax.net.ssl.HttpsURLConnection;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class Customer {
private String name;
private int points;
private String profilePhotoUrl;
public Customer(String name, int points) {
this(name, points, "");
}
public Customer(String name, int points, String profilePhotoUrl) {
this.name = name;
this.points = points;
this.profilePhotoUrl = profilePhotoUrl;
}
public String getName() {
return name;
}
public int getPoints() {
return points;
}
public boolean hasOver(int points) {
return this.points > points;
}
public boolean hasOverHundredPoints() {
return this.points > 100;
}
public boolean hasValidProfilePhoto() throws IOException {
URL url = new URL(this.profilePhotoUrl);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
return connection.getResponseCode() == HttpURLConnection.HTTP_OK;
}
public boolean hasValidProfilePhotoWithoutCheckedException() {
try {
URL url = new URL(this.profilePhotoUrl);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
return connection.getResponseCode() == HttpURLConnection.HTTP_OK;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@@ -0,0 +1,8 @@
package com.baeldung.stream.sum;
public class ArithmeticUtils {
public static int add(int a, int b) {
return a + b;
}
}
@@ -0,0 +1,31 @@
package com.baeldung.stream.sum;
public class Item {
private int id;
private Integer price;
public Item(int id, Integer price) {
super();
this.id = id;
this.price = price;
}
// Standard getters and setters
public long getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
}
@@ -0,0 +1,59 @@
package com.baeldung.stream.sum;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class StreamSumCalculator {
public static Integer getSumUsingCustomizedAccumulator(List<Integer> integers) {
return integers.stream()
.reduce(0, ArithmeticUtils::add);
}
public static Integer getSumUsingJavaAccumulator(List<Integer> integers) {
return integers.stream()
.reduce(0, Integer::sum);
}
public static Integer getSumUsingReduce(List<Integer> integers) {
return integers.stream()
.reduce(0, (a, b) -> a + b);
}
public static Integer getSumUsingCollect(List<Integer> integers) {
return integers.stream()
.collect(Collectors.summingInt(Integer::intValue));
}
public static Integer getSumUsingSum(List<Integer> integers) {
return integers.stream()
.mapToInt(Integer::intValue)
.sum();
}
public static Integer getSumOfMapValues(Map<Object, Integer> map) {
return map.values()
.stream()
.mapToInt(Integer::valueOf)
.sum();
}
public static Integer getSumIntegersFromString(String str) {
Integer sum = Arrays.stream(str.split(" "))
.filter((s) -> s.matches("\\d+"))
.mapToInt(Integer::valueOf)
.sum();
return sum;
}
}
@@ -0,0 +1,38 @@
package com.baeldung.stream.sum;
import java.util.List;
import java.util.stream.Collectors;
public class StreamSumCalculatorWithObject {
public static Integer getSumUsingCustomizedAccumulator(List<Item> items) {
return items.stream()
.map(x -> x.getPrice())
.reduce(0, ArithmeticUtils::add);
}
public static Integer getSumUsingJavaAccumulator(List<Item> items) {
return items.stream()
.map(x -> x.getPrice())
.reduce(0, Integer::sum);
}
public static Integer getSumUsingReduce(List<Item> items) {
return items.stream()
.map(item -> item.getPrice())
.reduce(0, (a, b) -> a + b);
}
public static Integer getSumUsingCollect(List<Item> items) {
return items.stream()
.map(x -> x.getPrice())
.collect(Collectors.summingInt(Integer::intValue));
}
public static Integer getSumUsingSum(List<Item> items) {
return items.stream()
.mapToInt(x -> x.getPrice())
.sum();
}
}