Compare commits
19 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 27db0d5540 | |||
| edcd08e1b2 | |||
| 038ce5b547 | |||
| b9d1b0257c | |||
| ddbb638242 | |||
| bf2335eda1 | |||
| 1b3b30cae3 | |||
| 4711c3a393 | |||
| 05d80c840d | |||
| 77c51720e9 | |||
| dc99d9404d | |||
| 2b1d680b2c | |||
| 3b344e5c9f | |||
| f2c3c2bf0f | |||
| b90cdd3306 | |||
| c816787e06 | |||
| e8f74069ff | |||
| ae29615530 | |||
| cd46aea7ac |
Generated
+9
-1
@@ -9,6 +9,7 @@
|
||||
<outputRelativeToContentRoot value="true" />
|
||||
<module name="codebank" />
|
||||
<module name="core-java-collections-list" />
|
||||
<module name="spring-data-jpa-repo-2" />
|
||||
<module name="core-java-streams" />
|
||||
<module name="assertion-libraries" />
|
||||
<module name="core-java-io" />
|
||||
@@ -16,8 +17,9 @@
|
||||
<module name="core-java-8-2" />
|
||||
<module name="core-java-numbers" />
|
||||
<module name="discourse" />
|
||||
<module name="core-java-11-2" />
|
||||
<module name="spring-data-redis" />
|
||||
<module name="core-java-strings" />
|
||||
<module name="core-java" />
|
||||
<module name="core-java-11" />
|
||||
<module name="core-java-collections-list-2" />
|
||||
<module name="core-java-collections" />
|
||||
@@ -27,8 +29,14 @@
|
||||
<module name="junit-5-basics" />
|
||||
<module name="core-java-collections-3" />
|
||||
<module name="core-java-collections-2" />
|
||||
<module name="activejdbc" />
|
||||
</profile>
|
||||
</annotationProcessing>
|
||||
<bytecodeTargetLevel>
|
||||
<module name="core-java-11-2" target="11" />
|
||||
<module name="hibernate-annotations" target="1.5" />
|
||||
<module name="hibernate5" target="11" />
|
||||
</bytecodeTargetLevel>
|
||||
</component>
|
||||
<component name="JavacSettings">
|
||||
<option name="ADDITIONAL_OPTIONS_OVERRIDE">
|
||||
|
||||
Generated
+12
@@ -33,8 +33,20 @@
|
||||
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-streams/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-strings/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-strings/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/core-java-modules/core-java/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/core-java-modules/core-java/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/core-java-modules/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/core-java-modules/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/persistence-modules/activejdbc/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/persistence-modules/activejdbc/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/persistence-modules/hibernate5/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/persistence-modules/hibernate5/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/persistence-modules/spring-data-jpa-repo-2/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/persistence-modules/spring-data-jpa-repo-2/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/persistence-modules/spring-data-redis/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/persistence-modules/spring-data-redis/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/persistence-modules/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/persistence-modules/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/testing-modules/assertion-libraries/src/main/java" charset="UTF-8" />
|
||||
|
||||
Generated
+20
@@ -1,11 +1,31 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="RemoteRepositoriesConfiguration">
|
||||
<remote-repository>
|
||||
<option name="id" value="ossez-repo-snapshots" />
|
||||
<option name="name" value="OSSEZ Private Snapshots" />
|
||||
<option name="url" value="https://repo.ossez.com/repository/maven-snapshots/" />
|
||||
</remote-repository>
|
||||
<remote-repository>
|
||||
<option name="id" value="central" />
|
||||
<option name="name" value="Central Repository" />
|
||||
<option name="url" value="https://repo.maven.apache.org/maven2" />
|
||||
</remote-repository>
|
||||
<remote-repository>
|
||||
<option name="id" value="geodb-repo" />
|
||||
<option name="name" value="GeoDB repository" />
|
||||
<option name="url" value="http://repo.boundlessgeo.com/main/" />
|
||||
</remote-repository>
|
||||
<remote-repository>
|
||||
<option name="id" value="ossez-repo-releases" />
|
||||
<option name="name" value="OSSEZ Private Releases" />
|
||||
<option name="url" value="https://repo.ossez.com/repository/maven-releases/" />
|
||||
</remote-repository>
|
||||
<remote-repository>
|
||||
<option name="id" value="central" />
|
||||
<option name="name" value="Central Repository" />
|
||||
<option name="url" value="https://repo.ossez.com/repository/maven-public/" />
|
||||
</remote-repository>
|
||||
<remote-repository>
|
||||
<option name="id" value="central" />
|
||||
<option name="name" value="Maven Central repository" />
|
||||
|
||||
Generated
+7
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="JpaBuddyIdeaProjectConfig">
|
||||
<option name="defaultUnitInitialized" value="true" />
|
||||
<option name="renamerInitialized" value="true" />
|
||||
</component>
|
||||
</project>
|
||||
Generated
+12
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="MessDetectorOptionsConfiguration">
|
||||
<option name="transferred" value="true" />
|
||||
</component>
|
||||
<component name="PHPCSFixerOptionsConfiguration">
|
||||
<option name="transferred" value="true" />
|
||||
</component>
|
||||
<component name="PHPCodeSnifferOptionsConfiguration">
|
||||
<option name="transferred" value="true" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -5,7 +5,7 @@
|
||||
<br>提供 CWIKI.US 项目中使用的代码
|
||||
</p>
|
||||
|
||||
所有的 Java 代码使用的是 JDK 11。
|
||||
Java 代码使用的是 JDK 11。
|
||||
|
||||
你可以通过单击下面连接后访问我们网站,并且访问我们提供的最新有关 Java 的开发资料。
|
||||
|
||||
@@ -25,7 +25,9 @@
|
||||
|
||||
# 公众平台
|
||||
|
||||
我们建议您通过社区论坛来和我们进行沟通,请关注我们公众平台上的账号
|
||||
我们建议您通过社区论坛来和我们进行沟通,请关注我们公众平台上的账号。
|
||||
|
||||
扫描 QR 关注我们的微信公众号和头条号。
|
||||
|
||||
## 微信公众号
|
||||
|
||||
@@ -33,10 +35,11 @@
|
||||
|
||||
## 头条号
|
||||
|
||||
我们也在头条号上创建了我们的公众号,请扫描下面的 QR 关注我们的头条号。
|
||||
|
||||

|
||||
|
||||
## 知乎
|
||||
请关注我们的知乎:https://www.zhihu.com/people/huyuchengus
|
||||
|
||||
## 快速导航
|
||||
|
||||
在下面的表格中,我们列出了一些比较有用的 CWIKIUS 相关软件开发使用教程的导航,欢迎访问下面的链接获得更多的内容和参与讨论
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
## 相关文章
|
||||
|
||||
- [J2EE,Java EE,Jakarta EE 命名之间的恩恩怨怨](https://www.ossez.com/t/j2ee-java-ee-jakarta-ee/14382)
|
||||
- [Understanding the NumberFormatException in Java](https://www.baeldung.com/java-number-format-exception)
|
||||
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
本模块中包含有关 Java 11 核心新增功能的的一些文章
|
||||
|
||||
### 相关文章
|
||||
- [Java 8 开始新增的 Optional 类](https://www.ossez.com/t/java-8-optional/13964)
|
||||
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
|
||||
- [Guide to Java 8’s Collectors](https://www.baeldung.com/java-8-collectors)
|
||||
- [New Features in Java 11](https://www.baeldung.com/java-11-new-features)
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
<version>${version.guava}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mock-server</groupId>
|
||||
|
||||
@@ -14,3 +14,4 @@ This module contains articles about Java 11 core features
|
||||
- [Negate a Predicate Method Reference with Java 11](https://www.baeldung.com/java-negate-predicate-method-reference)
|
||||
- [Benchmark JDK Collections vs Eclipse Collections](https://www.baeldung.com/jdk-collections-vs-eclipse-collections)
|
||||
- [Pre-compile Regex Patterns Into Pattern Objects](https://www.baeldung.com/java-regex-pre-compile)
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
<version>${version.guava}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
|
||||
本模块中包含有关 Java 8 核心新增功能特性的一些文章。
|
||||
|
||||
### 相关文章
|
||||
|
||||
### 相关文章
|
||||
- [Run a Java Application from the Command Line](https://www.baeldung.com/java-run-jar-with-arguments)
|
||||
- [Java 8 Stream skip() vs limit()](https://www.baeldung.com/java-stream-skip-vs-limit)
|
||||
- [Guide to Java BiFunction Interface](https://www.baeldung.com/java-bifunction-interface)
|
||||
- [Interface With Default Methods vs Abstract Class](https://www.baeldung.com/java-interface-default-method-vs-abstract-class)
|
||||
- [Convert Between Byte Array and UUID in Java](https://www.baeldung.com/java-byte-array-to-uuid)
|
||||
- [Create a Simple “Rock-Paper-Scissors” Game in Java](https://www.baeldung.com/java-rock-paper-scissors)
|
||||
- [Java 8 开始新增的 Optional 类](https://www.ossez.com/t/java-8-optional/13964)
|
||||
- [[<-- Java 8 核心(第 1 部分)]](/core-java-modules/core-java-8)
|
||||
|
||||
@@ -29,7 +29,7 @@
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
<version>${version.log4j}</version>
|
||||
</dependency>
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
|
||||
@@ -71,12 +71,12 @@
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
<version>${version.log4j}</version>
|
||||
</dependency>
|
||||
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${slf4j.version}</version>
|
||||
<version>${version.slf4j}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
package com.ossez.java9.compactstring;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static java.util.stream.Collectors.toList;
|
||||
|
||||
public class CompactStringDemo {
|
||||
|
||||
public static void main(String[] args) {
|
||||
long startTime = System.currentTimeMillis();
|
||||
List strings = IntStream.rangeClosed(1, 10_000_000).mapToObj(Integer::toString).collect(toList());
|
||||
long totalTime = System.currentTimeMillis() - startTime;
|
||||
System.out.println("Generated " + strings.size() + " strings in " + totalTime + " ms.");
|
||||
|
||||
startTime = System.currentTimeMillis();
|
||||
String appended = (String) strings.stream().limit(100_000).reduce("", (left, right) -> left.toString() + right.toString());
|
||||
totalTime = System.currentTimeMillis() - startTime;
|
||||
System.out.println("Created string of length " + appended.length() + " in " + totalTime + " ms.");
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
package com.ossez.localization;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
public class App {
|
||||
|
||||
/**
|
||||
* Runs all available formatter
|
||||
* @throws ParseException
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
List<Locale> locales = Arrays.asList(new Locale[] { Locale.UK, Locale.ITALY, Locale.FRANCE, Locale.forLanguageTag("pl-PL") });
|
||||
Localization.run(locales);
|
||||
JavaSEFormat.run(locales);
|
||||
ICUFormat.run(locales);
|
||||
}
|
||||
|
||||
}
|
||||
-29
@@ -1,29 +0,0 @@
|
||||
package com.ossez.localization;
|
||||
|
||||
import com.ibm.icu.text.MessageFormat;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.ResourceBundle;
|
||||
|
||||
public class ICUFormat {
|
||||
|
||||
public static String getLabel(Locale locale, Object[] data) {
|
||||
ResourceBundle bundle = ResourceBundle.getBundle("formats", locale);
|
||||
String format = bundle.getString("label-icu");
|
||||
MessageFormat formatter = new MessageFormat(format, locale);
|
||||
return formatter.format(data);
|
||||
}
|
||||
|
||||
public static void run(List<Locale> locales) {
|
||||
System.out.println("ICU formatter");
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Alice", "female", 0 })));
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Alice", "female", 1 })));
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Alice", "female", 2 })));
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Alice", "female", 3 })));
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Bob", "male", 0 })));
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Bob", "male", 1 })));
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Bob", "male", 2 })));
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Bob", "male", 3 })));
|
||||
}
|
||||
}
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
package com.ossez.localization;
|
||||
|
||||
import java.text.MessageFormat;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.ResourceBundle;
|
||||
|
||||
public class JavaSEFormat {
|
||||
|
||||
public static String getLabel(Locale locale, Object[] data) {
|
||||
ResourceBundle bundle = ResourceBundle.getBundle("formats", locale);
|
||||
final String pattern = bundle.getString("label");
|
||||
final MessageFormat formatter = new MessageFormat(pattern, locale);
|
||||
return formatter.format(data);
|
||||
}
|
||||
|
||||
public static void run(List<Locale> locales) {
|
||||
System.out.println("Java formatter");
|
||||
final Date date = new Date(System.currentTimeMillis());
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { date, "Alice", 0 })));
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { date, "Alice", 2 })));
|
||||
}
|
||||
}
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
package com.ossez.localization;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.ResourceBundle;
|
||||
|
||||
public class Localization {
|
||||
|
||||
public static String getLabel(Locale locale) {
|
||||
final ResourceBundle bundle = ResourceBundle.getBundle("messages", locale);
|
||||
return bundle.getString("label");
|
||||
}
|
||||
|
||||
public static void run(List<Locale> locales) {
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale)));
|
||||
}
|
||||
|
||||
}
|
||||
-198
@@ -1,198 +0,0 @@
|
||||
package com.ossez.stringperformance;
|
||||
|
||||
import com.google.common.base.Splitter;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.StringTokenizer;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@BenchmarkMode(Mode.SingleShotTime)
|
||||
@OutputTimeUnit(TimeUnit.MILLISECONDS)
|
||||
@Measurement(batchSize = 100000, iterations = 10)
|
||||
@Warmup(batchSize = 100000, iterations = 10)
|
||||
@State(Scope.Thread)
|
||||
public class StringPerformance {
|
||||
|
||||
protected String baeldung = "baeldung";
|
||||
protected String longString = "Hello baeldung, I am a bit longer than other Strings";
|
||||
protected String formatString = "hello %s, nice to meet you";
|
||||
protected String formatDigit = "%d";
|
||||
protected String emptyString = " ";
|
||||
protected String result = "";
|
||||
|
||||
protected int sampleNumber = 100;
|
||||
|
||||
protected Pattern spacePattern = Pattern.compile(emptyString);
|
||||
protected Pattern longPattern = Pattern.compile(longString);
|
||||
protected List<String> stringSplit = new ArrayList<>();
|
||||
protected List<String> stringTokenizer = new ArrayList<>();
|
||||
|
||||
@Benchmark
|
||||
public String benchmarkStringDynamicConcat() {
|
||||
result += baeldung;
|
||||
return result;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public StringBuilder benchmarkStringBuilder() {
|
||||
StringBuilder stringBuilder = new StringBuilder(result);
|
||||
stringBuilder.append(baeldung);
|
||||
return stringBuilder;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public StringBuffer benchmarkStringBuffer() {
|
||||
StringBuffer stringBuffer = new StringBuffer(result);
|
||||
stringBuffer.append(baeldung);
|
||||
return stringBuffer;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String benchmarkStringConstructor() {
|
||||
String result = new String("baeldung");
|
||||
return result;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String benchmarkStringLiteral() {
|
||||
String result = "baeldung";
|
||||
return result;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String benchmarkStringFormat_s() {
|
||||
return String.format(formatString, baeldung);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String benchmarkStringConcat() {
|
||||
result = result.concat(baeldung);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String benchmarkStringIntern() {
|
||||
return baeldung.intern();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String benchmarkStringReplace() {
|
||||
return longString.replace("average", " average !!!");
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String benchmarkStringUtilsReplace() {
|
||||
return StringUtils.replace(longString, "average", " average !!!");
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public List<String> benchmarkGuavaSplitter() {
|
||||
return Splitter.on(" ").trimResults()
|
||||
.omitEmptyStrings()
|
||||
.splitToList(longString);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String [] benchmarkStringSplit() {
|
||||
return longString.split(emptyString);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String [] benchmarkStringSplitPattern() {
|
||||
return spacePattern.split(longString, 0);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public List benchmarkStringTokenizer() {
|
||||
StringTokenizer st = new StringTokenizer(longString);
|
||||
while (st.hasMoreTokens()) {
|
||||
stringTokenizer.add(st.nextToken());
|
||||
}
|
||||
return stringTokenizer;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public List benchmarkStringIndexOf() {
|
||||
int pos = 0, end;
|
||||
while ((end = longString.indexOf(' ', pos)) >= 0) {
|
||||
stringSplit.add(longString.substring(pos, end));
|
||||
pos = end + 1;
|
||||
}
|
||||
//Add last token of string
|
||||
stringSplit.add(longString.substring(pos));
|
||||
return stringSplit;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String benchmarkIntegerToString() {
|
||||
return Integer.toString(sampleNumber);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String benchmarkStringValueOf() {
|
||||
return String.valueOf(sampleNumber);
|
||||
}
|
||||
|
||||
|
||||
@Benchmark
|
||||
public String benchmarkStringConvertPlus() {
|
||||
return sampleNumber + "";
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String benchmarkStringFormat_d() {
|
||||
return String.format(formatDigit, sampleNumber);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean benchmarkStringEquals() {
|
||||
return longString.equals(baeldung);
|
||||
}
|
||||
|
||||
|
||||
@Benchmark
|
||||
public boolean benchmarkStringEqualsIgnoreCase() {
|
||||
return longString.equalsIgnoreCase(baeldung);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean benchmarkStringMatches() {
|
||||
return longString.matches(baeldung);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean benchmarkPrecompiledMatches() {
|
||||
return longPattern.matcher(baeldung).matches();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int benchmarkStringCompareTo() {
|
||||
return longString.compareTo(baeldung);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean benchmarkStringIsEmpty() {
|
||||
return longString.isEmpty();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean benchmarkStringLengthZero() {
|
||||
return longString.length() == 0;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Options options = new OptionsBuilder()
|
||||
.include(StringPerformance.class.getSimpleName()).threads(1)
|
||||
.forks(1).shouldFailOnError(true)
|
||||
.shouldDoGC(true)
|
||||
.jvmArgs("-server").build();
|
||||
new Runner(options).run();
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -1,2 +0,0 @@
|
||||
label=On {0, date, short} {1} has sent you {2, choice, 0#no messages|1#a message|2#two messages|2<{2,number,integer} messages}.
|
||||
label-icu={0} has sent you {2, plural, =0 {no messages} =1 {a message} other {{2, number, integer} messages}}.
|
||||
@@ -1,2 +0,0 @@
|
||||
label={0, date, short}, {1}{2, choice, 0# ne|0<} vous a envoy\u00e9 {2, choice, 0#aucun message|1#un message|2#deux messages|2<{2,number,integer} messages}.
|
||||
label-icu={0} {2, plural, =0 {ne } other {}}vous a envoy\u00e9 {2, plural, =0 {aucun message} =1 {un message} other {{2, number, integer} messages}}.
|
||||
@@ -1,2 +0,0 @@
|
||||
label={0, date, short} {1} ti ha inviato {2, choice, 0#nessun messagio|1#un messaggio|2#due messaggi|2<{2, number, integer} messaggi}.
|
||||
label-icu={0} {2, plural, =0 {non } other {}}ti ha inviato {2, plural, =0 {nessun messaggio} =1 {un messaggio} other {{2, number, integer} messaggi}}.
|
||||
@@ -1,2 +0,0 @@
|
||||
label=W {0, date, short} {1}{2, choice, 0# nie|0<} wys\u0142a\u0142a ci {2, choice, 0#\u017Cadnych wiadomo\u015Bci|1#wiadomo\u015B\u0107|2#dwie wiadomo\u015Bci|2<{2, number, integer} wiadomo\u015Bci}.
|
||||
label-icu={0} {2, plural, =0 {nie } other {}}{1, select, male {wys\u0142a\u0142} female {wys\u0142a\u0142a} other {wys\u0142a\u0142o}} ci {2, plural, =0 {\u017Cadnej wiadomo\u015Bci} =1 {wiadomo\u015B\u0107} other {{2, number, integer} wiadomo\u015Bci}}.
|
||||
@@ -1 +0,0 @@
|
||||
label=Alice has sent you a message.
|
||||
@@ -1 +0,0 @@
|
||||
label=Alice vous a envoy\u00e9 un message.
|
||||
@@ -1 +0,0 @@
|
||||
label=Alice ti ha inviato un messaggio.
|
||||
@@ -1 +0,0 @@
|
||||
label=Alice wys\u0142a\u0142a ci wiadomo\u015B\u0107.
|
||||
@@ -1,4 +0,0 @@
|
||||
Get busy living
|
||||
or
|
||||
get busy dying.
|
||||
--Stephen King
|
||||
-20
@@ -1,20 +0,0 @@
|
||||
package com.ossez.interview;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.text.NumberFormat;
|
||||
import java.util.Locale;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class LocaleUnitTest {
|
||||
@Test
|
||||
public void whenUsingLocal_thenCorrectResultsForDifferentLocale() {
|
||||
Locale usLocale = Locale.US;
|
||||
BigDecimal number = new BigDecimal(102_300.456d);
|
||||
|
||||
NumberFormat usNumberFormat = NumberFormat.getCurrencyInstance(usLocale);
|
||||
assertEquals(usNumberFormat.format(number), "$102,300.46");
|
||||
}
|
||||
}
|
||||
-29
@@ -1,29 +0,0 @@
|
||||
package com.ossez.interview;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class StringAnagramUnitTest {
|
||||
public boolean isAnagram(String s1, String s2) {
|
||||
if(s1.length() != s2.length())
|
||||
return false;
|
||||
|
||||
char[] arr1 = s1.toCharArray();
|
||||
char[] arr2 = s2.toCharArray();
|
||||
|
||||
Arrays.sort(arr1);
|
||||
Arrays.sort(arr2);
|
||||
|
||||
return Arrays.equals(arr1, arr2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTestAnagrams_thenTestingCorrectly() {
|
||||
assertThat(isAnagram("car", "arc")).isTrue();
|
||||
assertThat(isAnagram("west", "stew")).isTrue();
|
||||
assertThat(isAnagram("west", "east")).isFalse();
|
||||
}
|
||||
}
|
||||
-20
@@ -1,20 +0,0 @@
|
||||
package com.ossez.interview;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class StringChangeCaseUnitTest {
|
||||
@Test
|
||||
public void givenString_whenChangingToUppercase_thenCaseChanged() {
|
||||
String s = "Welcome to Baeldung!";
|
||||
assertEquals("WELCOME TO BAELDUNG!", s.toUpperCase());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenString_whenChangingToLowerrcase_thenCaseChanged() {
|
||||
String s = "Welcome to Baeldung!";
|
||||
assertEquals("welcome to baeldung!", s.toLowerCase());
|
||||
}
|
||||
}
|
||||
-28
@@ -1,28 +0,0 @@
|
||||
package com.ossez.interview;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class StringCountOccurrencesUnitTest {
|
||||
public int countOccurrences(String s, char c) {
|
||||
int count = 0;
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
if (s.charAt(i) == c) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenCountingFrequencyOfChar_thenCountCorrect() {
|
||||
assertEquals(3, countOccurrences("united states", 't'));
|
||||
}
|
||||
|
||||
public void givenString_whenUsingJava8_thenCountingOfCharCorrect() {
|
||||
String str = "united states";
|
||||
long count = str.chars().filter(ch -> (char)ch == 't').count();
|
||||
assertEquals(3, count);
|
||||
}
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
package com.ossez.interview;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class StringFormatUnitTest {
|
||||
@Test
|
||||
public void givenString_whenUsingStringFormat_thenStringFormatted() {
|
||||
String title = "Baeldung";
|
||||
String formatted = String.format("Title is %s", title);
|
||||
assertEquals(formatted, "Title is Baeldung");
|
||||
}
|
||||
}
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
package com.ossez.interview;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class StringInternUnitTest {
|
||||
@Test
|
||||
public void whenCallingStringIntern_thenStringsInterned() {
|
||||
String s1 = "Baeldung";
|
||||
String s2 = new String("Baeldung");
|
||||
String s3 = new String("Baeldung").intern();
|
||||
|
||||
assertThat(s1 == s2).isFalse();
|
||||
assertThat(s1 == s3).isTrue();
|
||||
}
|
||||
}
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
package com.ossez.interview;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.StringJoiner;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class StringJoinerUnitTest {
|
||||
@Test
|
||||
public void whenUsingStringJoiner_thenStringsJoined() {
|
||||
StringJoiner joiner = new StringJoiner(",", "[", "]");
|
||||
joiner.add("Red")
|
||||
.add("Green")
|
||||
.add("Blue");
|
||||
|
||||
assertEquals(joiner.toString(), "[Red,Green,Blue]");
|
||||
}
|
||||
}
|
||||
-29
@@ -1,29 +0,0 @@
|
||||
package com.ossez.interview;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class StringPalindromeUnitTest {
|
||||
|
||||
public boolean isPalindrome(String text) {
|
||||
int forward = 0;
|
||||
int backward = text.length() - 1;
|
||||
while (backward > forward) {
|
||||
char forwardChar = text.charAt(forward++);
|
||||
char backwardChar = text.charAt(backward--);
|
||||
if (forwardChar != backwardChar)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIsPalindromeMethod_whenCheckingString_thenFindIfPalindrome() {
|
||||
assertThat(isPalindrome("madam")).isTrue();
|
||||
assertThat(isPalindrome("radar")).isTrue();
|
||||
assertThat(isPalindrome("level")).isTrue();
|
||||
|
||||
assertThat(isPalindrome("baeldung")).isFalse();
|
||||
}
|
||||
}
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
package com.ossez.interview;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class StringReverseUnitTest {
|
||||
@Test
|
||||
public void whenUsingInbuildMethods_thenStringReversed() {
|
||||
String reversed = new StringBuilder("baeldung").reverse().toString();
|
||||
assertEquals("gnudleab", reversed);
|
||||
}
|
||||
}
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
package com.ossez.interview;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
|
||||
public class StringSplitUnitTest {
|
||||
@Test
|
||||
public void givenCoreJava_whenSplittingStrings_thenSplitted() {
|
||||
String expected[] = {
|
||||
"john",
|
||||
"peter",
|
||||
"mary"
|
||||
};
|
||||
|
||||
String[] splitted = "john,peter,mary".split(",");
|
||||
assertArrayEquals( expected, splitted );
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenApacheCommons_whenSplittingStrings_thenSplitted() {
|
||||
String expected[] = {
|
||||
"john",
|
||||
"peter",
|
||||
"mary"
|
||||
};
|
||||
String[] splitted = StringUtils.split("john peter mary");
|
||||
assertArrayEquals( expected, splitted );
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
package com.ossez.interview;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
|
||||
public class StringToByteArrayUnitTest {
|
||||
@Test
|
||||
public void whenGetBytes_thenCorrect() throws UnsupportedEncodingException {
|
||||
byte[] byteArray1 = "abcd".getBytes();
|
||||
byte[] byteArray2 = "efgh".getBytes(StandardCharsets.US_ASCII);
|
||||
byte[] byteArray3 = "ijkl".getBytes("UTF-8");
|
||||
byte[] expected1 = new byte[] { 97, 98, 99, 100 };
|
||||
byte[] expected2 = new byte[] { 101, 102, 103, 104 };
|
||||
byte[] expected3 = new byte[] { 105, 106, 107, 108 };
|
||||
|
||||
assertArrayEquals(expected1, byteArray1);
|
||||
assertArrayEquals(expected2, byteArray2);
|
||||
assertArrayEquals(expected3, byteArray3);
|
||||
}
|
||||
}
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
package com.ossez.interview;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class StringToCharArrayUnitTest {
|
||||
@Test
|
||||
public void whenConvertingStringToCharArray_thenConversionSuccessful() {
|
||||
String beforeConvStr = "hello";
|
||||
char[] afterConvCharArr = { 'h', 'e', 'l', 'l', 'o' };
|
||||
|
||||
assertEquals(Arrays.equals(beforeConvStr.toCharArray(), afterConvCharArr), true);
|
||||
}
|
||||
}
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
package com.ossez.interview;
|
||||
|
||||
import org.apache.commons.lang3.math.NumberUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class StringToIntegerUnitTest {
|
||||
@Test
|
||||
public void givenString_whenParsingInt_shouldConvertToInt() {
|
||||
String givenString = "42";
|
||||
|
||||
int result = Integer.parseInt(givenString);
|
||||
|
||||
assertThat(result).isEqualTo(42);
|
||||
}
|
||||
}
|
||||
-72
@@ -1,72 +0,0 @@
|
||||
package com.ossez.localization;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class ICUFormatUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenInUK_whenAliceSendsNothing_thenCorrectMessage() {
|
||||
assertEquals("Alice has sent you no messages.", ICUFormat.getLabel(Locale.UK, new Object[] { "Alice", "female", 0 }));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInUK_whenAliceSendsOneMessage_thenCorrectMessage() {
|
||||
assertEquals("Alice has sent you a message.", ICUFormat.getLabel(Locale.UK, new Object[] { "Alice", "female", 1 }));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInUK_whenBobSendsSixMessages_thenCorrectMessage() {
|
||||
assertEquals("Bob has sent you 6 messages.", ICUFormat.getLabel(Locale.UK, new Object[] { "Bob", "male", 6 }));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInItaly_whenAliceSendsNothing_thenCorrectMessage() {
|
||||
assertEquals("Alice non ti ha inviato nessun messaggio.", ICUFormat.getLabel(Locale.ITALY, new Object[] { "Alice", "female", 0 }));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInItaly_whenAliceSendsOneMessage_thenCorrectMessage() {
|
||||
assertEquals("Alice ti ha inviato un messaggio.", ICUFormat.getLabel(Locale.ITALY, new Object[] { "Alice", "female", 1 }));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInItaly_whenBobSendsSixMessages_thenCorrectMessage() {
|
||||
assertEquals("Bob ti ha inviato 6 messaggi.", ICUFormat.getLabel(Locale.ITALY, new Object[] { "Bob", "male", 6 }));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInFrance_whenAliceSendsNothing_thenCorrectMessage() {
|
||||
assertEquals("Alice ne vous a envoyé aucun message.", ICUFormat.getLabel(Locale.FRANCE, new Object[] { "Alice", "female", 0 }));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInFrance_whenAliceSendsOneMessage_thenCorrectMessage() {
|
||||
assertEquals("Alice vous a envoyé un message.", ICUFormat.getLabel(Locale.FRANCE, new Object[] { "Alice", "female", 1 }));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInFrance_whenBobSendsSixMessages_thenCorrectMessage() {
|
||||
assertEquals("Bob vous a envoyé 6 messages.", ICUFormat.getLabel(Locale.FRANCE, new Object[] { "Bob", "male", 6 }));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenInPoland_whenAliceSendsNothing_thenCorrectMessage() {
|
||||
assertEquals("Alice nie wysłała ci żadnej wiadomości.", ICUFormat.getLabel(Locale.forLanguageTag("pl-PL"), new Object[] { "Alice", "female", 0 }));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInPoland_whenAliceSendsOneMessage_thenCorrectMessage() {
|
||||
assertEquals("Alice wysłała ci wiadomość.", ICUFormat.getLabel(Locale.forLanguageTag("pl-PL"), new Object[] { "Alice", "female", 1 }));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInPoland_whenBobSendsSixMessages_thenCorrectMessage() {
|
||||
assertEquals("Bob wysłał ci 6 wiadomości.", ICUFormat.getLabel(Locale.forLanguageTag("pl-PL"), new Object[] { "Bob", "male", 6 }));
|
||||
}
|
||||
|
||||
}
|
||||
-103
@@ -1,103 +0,0 @@
|
||||
package com.ossez.randomstrings;
|
||||
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.Random;
|
||||
|
||||
public class RandomStringsUnitTest {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(RandomStringsUnitTest.class);
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenGeneratingRandomStringUnbounded_thenCorrect() {
|
||||
byte[] array = new byte[7]; // length is bounded by 7
|
||||
new Random().nextBytes(array);
|
||||
String generatedString = new String(array, Charset.forName("UTF-8"));
|
||||
|
||||
LOG.debug(generatedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenGeneratingRandomStringBounded_thenCorrect() {
|
||||
int leftLimit = 97; // letter 'a'
|
||||
int rightLimit = 122; // letter 'z'
|
||||
int targetStringLength = 10;
|
||||
Random random = new Random();
|
||||
StringBuilder buffer = new StringBuilder(targetStringLength);
|
||||
|
||||
for (int i = 0; i < targetStringLength; i++) {
|
||||
int randomLimitedInt = leftLimit + (int) (random.nextFloat() * (rightLimit - leftLimit + 1));
|
||||
buffer.append((char) randomLimitedInt);
|
||||
}
|
||||
String generatedString = buffer.toString();
|
||||
|
||||
LOG.debug(generatedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingJava8_whenGeneratingRandomAlphabeticString_thenCorrect() {
|
||||
int leftLimit = 97; // letter 'a'
|
||||
int rightLimit = 122; // letter 'z'
|
||||
int targetStringLength = 10;
|
||||
Random random = new Random();
|
||||
|
||||
String generatedString = random.ints(leftLimit, rightLimit + 1)
|
||||
.limit(targetStringLength)
|
||||
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
|
||||
.toString();
|
||||
|
||||
LOG.debug(generatedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingJava8_whenGeneratingRandomAlphanumericString_thenCorrect() {
|
||||
int leftLimit = 48; // numeral '0'
|
||||
int rightLimit = 122; // letter 'z'
|
||||
int targetStringLength = 10;
|
||||
Random random = new Random();
|
||||
|
||||
String generatedString = random.ints(leftLimit, rightLimit + 1)
|
||||
.filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97))
|
||||
.limit(targetStringLength)
|
||||
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
|
||||
.toString();
|
||||
|
||||
LOG.debug(generatedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApache_whenGeneratingRandomString_thenCorrect() {
|
||||
String generatedString = RandomStringUtils.random(10);
|
||||
|
||||
LOG.debug(generatedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApache_whenGeneratingRandomAlphabeticString_thenCorrect() {
|
||||
String generatedString = RandomStringUtils.randomAlphabetic(10);
|
||||
|
||||
LOG.debug(generatedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApache_whenGeneratingRandomAlphanumericString_thenCorrect() {
|
||||
String generatedString = RandomStringUtils.randomAlphanumeric(10);
|
||||
|
||||
LOG.debug(generatedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApache_whenGeneratingRandomStringBounded_thenCorrect() {
|
||||
int length = 10;
|
||||
boolean useLetters = true;
|
||||
boolean useNumbers = false;
|
||||
String generatedString = RandomStringUtils.random(length, useLetters, useNumbers);
|
||||
|
||||
LOG.debug(generatedString);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
## Core Java streams
|
||||
|
||||
This module contains articles about the Stream API in Java.
|
||||
|
||||
### Relevant Articles:
|
||||
- [The Java 8 Stream API Tutorial](https://www.baeldung.com/java-8-streams)
|
||||
- [Introduction to Java 8 Streams](https://www.baeldung.com/java-8-streams-introduction)
|
||||
- [Java 8 Stream findFirst() vs. findAny()](https://www.baeldung.com/java-stream-findfirst-vs-findany)
|
||||
- [Guide to Stream.reduce()](https://www.baeldung.com/java-stream-reduce)
|
||||
- [Java IntStream Conversions](https://www.baeldung.com/java-intstream-convert)
|
||||
- [Java 8 Streams peek() API](https://www.baeldung.com/java-streams-peek-api)
|
||||
- [Working With Maps Using Streams](https://www.baeldung.com/java-maps-streams)
|
||||
- [Collect a Java Stream to an Immutable Collection](https://www.baeldung.com/java-stream-immutable-collection)
|
||||
- [How to Add a Single Element to a Stream](https://www.baeldung.com/java-stream-append-prepend)
|
||||
- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream)
|
||||
- More articles: [[<-- prev>]](/../core-java-streams) [[next -->]](/../core-java-streams-3)
|
||||
@@ -1,40 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-streams-2</artifactId>
|
||||
<version>1.0</version>
|
||||
<name>core-java-streams-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh-generator.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>1.9</maven.compiler.source>
|
||||
<maven.compiler.target>1.9</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
-39
@@ -1,39 +0,0 @@
|
||||
package com.baeldung.reduce.application;
|
||||
|
||||
import com.baeldung.reduce.entities.User;
|
||||
import com.baeldung.reduce.utilities.NumberUtils;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
-52
@@ -1,52 +0,0 @@
|
||||
package com.baeldung.reduce.benchmarks;
|
||||
|
||||
import com.baeldung.reduce.entities.User;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||
import org.openjdk.jmh.annotations.Mode;
|
||||
import org.openjdk.jmh.annotations.Scope;
|
||||
import org.openjdk.jmh.annotations.State;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.RunnerException;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
@State(Scope.Thread)
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public class JMHStreamReduceBenchMark {
|
||||
|
||||
private final List<User> userList = createUsers();
|
||||
|
||||
public static void main(String[] args) throws RunnerException {
|
||||
|
||||
Options options = new OptionsBuilder()
|
||||
.include(JMHStreamReduceBenchMark.class.getSimpleName()).threads(1)
|
||||
.forks(1).shouldFailOnError(true).shouldDoGC(true)
|
||||
.jvmArgs("-server").build();
|
||||
new Runner(options).run();
|
||||
}
|
||||
|
||||
private List<User> createUsers() {
|
||||
List<User> users = new ArrayList<>();
|
||||
for (int i = 0; i <= 1000000; i++) {
|
||||
users.add(new User("John" + i, i));
|
||||
}
|
||||
return users;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Integer executeReduceOnParallelizedStream() {
|
||||
return this.userList
|
||||
.parallelStream()
|
||||
.reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Integer executeReduceOnSequentialStream() {
|
||||
return this.userList
|
||||
.stream()
|
||||
.reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
||||
}
|
||||
}
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
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 + '}';
|
||||
}
|
||||
}
|
||||
-52
@@ -1,52 +0,0 @@
|
||||
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 thrown!");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
package com.baeldung.streams;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collector;
|
||||
|
||||
public class MyImmutableListCollector {
|
||||
|
||||
public static <T, A extends List<T>> Collector<T, A, List<T>> toImmutableList(Supplier<A> supplier) {
|
||||
return Collector.of(supplier, List::add, (left, right) -> {
|
||||
left.addAll(right);
|
||||
return left;
|
||||
}, Collections::unmodifiableList);
|
||||
}
|
||||
|
||||
public static <T> Collector<T, List<T>, List<T>> toImmutableList() {
|
||||
return toImmutableList(ArrayList::new);
|
||||
}
|
||||
|
||||
}
|
||||
-40
@@ -1,40 +0,0 @@
|
||||
package com.baeldung.convert.intstreams;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class IntStreamsConversionsUnitTest {
|
||||
|
||||
@Test
|
||||
public void intStreamToArray() {
|
||||
int[] first50EvenNumbers = IntStream.iterate(0, i -> i + 2)
|
||||
.limit(50)
|
||||
.toArray();
|
||||
|
||||
assertThat(first50EvenNumbers).hasSize(50);
|
||||
assertThat(first50EvenNumbers[2]).isEqualTo(4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void intStreamToList() {
|
||||
List<Integer> first50IntegerNumbers = IntStream.range(0, 50)
|
||||
.boxed()
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(first50IntegerNumbers).hasSize(50);
|
||||
assertThat(first50IntegerNumbers.get(2)).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void intStreamToString() {
|
||||
String first3numbers = IntStream.of(0, 1, 2)
|
||||
.mapToObj(String::valueOf)
|
||||
.collect(Collectors.joining(", ", "[", "]"));
|
||||
|
||||
assertThat(first3numbers).isEqualTo("[0, 1, 2]");
|
||||
}
|
||||
}
|
||||
-80
@@ -1,80 +0,0 @@
|
||||
package com.baeldung.reduce;
|
||||
|
||||
import com.baeldung.reduce.entities.User;
|
||||
import com.baeldung.reduce.utilities.NumberUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class StreamReduceUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenIntegerList_whenReduceWithSumAccumulatorLambda_thenCorrect() {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||
int result = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element);
|
||||
assertThat(result).isEqualTo(21);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntegerList_whenReduceWithSumAccumulatorMethodReference_thenCorrect() {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||
int result = numbers.stream().reduce(0, Integer::sum);
|
||||
assertThat(result).isEqualTo(21);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringList_whenReduceWithConcatenatorAccumulatorLambda_thenCorrect() {
|
||||
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
||||
String result = letters.stream().reduce("", (partialString, element) -> partialString + element);
|
||||
assertThat(result).isEqualTo("abcde");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringList_whenReduceWithConcatenatorAccumulatorMethodReference_thenCorrect() {
|
||||
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
||||
String result = letters.stream().reduce("", String::concat);
|
||||
assertThat(result).isEqualTo("abcde");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringList_whenReduceWithUppercaseConcatenatorAccumulator_thenCorrect() {
|
||||
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
||||
String result = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase());
|
||||
assertThat(result).isEqualTo("ABCDE");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUserList_whenReduceWithAgeAccumulatorAndSumCombiner_thenCorrect() {
|
||||
List<User> users = Arrays.asList(new User("John", 30), new User("Julie", 35));
|
||||
int result = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
||||
assertThat(result).isEqualTo(65);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringList_whenReduceWithParallelStream_thenCorrect() {
|
||||
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
||||
String result = letters.parallelStream().reduce("", String::concat);
|
||||
assertThat(result).isEqualTo("abcde");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNumberUtilsClass_whenCalledDivideListElements_thenCorrect() {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||
assertThat(NumberUtils.divideListElements(numbers, 1)).isEqualTo(21);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlock_thenCorrect() {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||
assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 1)).isEqualTo(21);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStream_whneCalleddivideListElementsWithApplyFunctionMethod_thenCorrect() {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||
assertThat(NumberUtils.divideListElementsWithApplyFunctionMethod(numbers, 1)).isEqualTo(21);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package com.baeldung.streams;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
-46
@@ -1,46 +0,0 @@
|
||||
package com.baeldung.streams;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.hamcrest.Matchers.anyOf;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class Java8FindAnyFindFirstUnitTest {
|
||||
|
||||
@Test
|
||||
public void createStream_whenFindAnyResultIsPresent_thenCorrect() {
|
||||
|
||||
List<String> list = Arrays.asList("A", "B", "C", "D");
|
||||
|
||||
Optional<String> result = list.stream().findAny();
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
assertThat(result.get(), anyOf(is("A"), is("B"), is("C"), is("D")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createParallelStream_whenFindAnyResultIsPresent_thenCorrect() throws Exception {
|
||||
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
|
||||
Optional<Integer> result = list.stream().parallel().filter(num -> num < 4).findAny();
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
assertThat(result.get(), anyOf(is(1), is(2), is(3)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createStream_whenFindFirstResultIsPresent_thenCorrect() {
|
||||
|
||||
List<String> list = Arrays.asList("A", "B", "C", "D");
|
||||
|
||||
Optional<String> result = list.stream().findFirst();
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
assertThat(result.get(), is("A"));
|
||||
}
|
||||
}
|
||||
-242
@@ -1,242 +0,0 @@
|
||||
package com.baeldung.streams;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.*;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class Java8StreamApiUnitTest {
|
||||
|
||||
private long counter;
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(Java8StreamApiUnitTest.class);
|
||||
|
||||
private List<Product> productList;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
productList = Arrays.asList(new Product(23, "potatoes"), new Product(14, "orange"), new Product(13, "lemon"), new Product(23, "bread"), new Product(13, "sugar"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkPipeline_whenStreamOneElementShorter_thenCorrect() {
|
||||
|
||||
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
|
||||
long size = list.stream().skip(1).map(element -> element.substring(0, 3)).count();
|
||||
assertEquals(list.size() - 1, size);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkOrder_whenChangeQuantityOfMethodCalls_thenCorrect() {
|
||||
|
||||
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
|
||||
|
||||
counter = 0;
|
||||
long sizeFirst = list.stream().skip(2).map(element -> {
|
||||
wasCalled();
|
||||
return element.substring(0, 3);
|
||||
}).count();
|
||||
assertEquals(1, counter);
|
||||
|
||||
counter = 0;
|
||||
long sizeSecond = list.stream().map(element -> {
|
||||
wasCalled();
|
||||
return element.substring(0, 3);
|
||||
}).skip(2).count();
|
||||
assertEquals(3, counter);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createEmptyStream_whenEmpty_thenCorrect() {
|
||||
|
||||
Stream<String> streamEmpty = Stream.empty();
|
||||
assertEquals(0, streamEmpty.count());
|
||||
|
||||
List<String> names = Collections.emptyList();
|
||||
Stream<String> streamOf = Product.streamOf(names);
|
||||
assertTrue(streamOf.count() == 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createStream_whenCreated_thenCorrect() {
|
||||
|
||||
Collection<String> collection = Arrays.asList("a", "b", "c");
|
||||
Stream<String> streamOfCollection = collection.stream();
|
||||
assertEquals(3, streamOfCollection.count());
|
||||
|
||||
Stream<String> streamOfArray = Stream.of("a", "b", "c");
|
||||
assertEquals(3, streamOfArray.count());
|
||||
|
||||
String[] arr = new String[] { "a", "b", "c" };
|
||||
Stream<String> streamOfArrayPart = Arrays.stream(arr, 1, 3);
|
||||
assertEquals(2, streamOfArrayPart.count());
|
||||
|
||||
IntStream intStream = IntStream.range(1, 3);
|
||||
LongStream longStream = LongStream.rangeClosed(1, 3);
|
||||
Random random = new Random();
|
||||
DoubleStream doubleStream = random.doubles(3);
|
||||
assertEquals(2, intStream.count());
|
||||
assertEquals(3, longStream.count());
|
||||
assertEquals(3, doubleStream.count());
|
||||
|
||||
IntStream streamOfChars = "abc".chars();
|
||||
IntStream str = "".chars();
|
||||
assertEquals(3, streamOfChars.count());
|
||||
|
||||
Stream<String> streamOfString = Pattern.compile(", ").splitAsStream("a, b, c");
|
||||
assertEquals("a", streamOfString.findFirst().get());
|
||||
|
||||
Path path = getPath();
|
||||
Stream<String> streamOfStrings = null;
|
||||
try {
|
||||
streamOfStrings = Files.lines(path, Charset.forName("UTF-8"));
|
||||
} catch (IOException e) {
|
||||
log.error("Error creating streams from paths {}", path, e.getMessage(), e);
|
||||
}
|
||||
assertEquals("a", streamOfStrings.findFirst().get());
|
||||
|
||||
Stream<String> streamBuilder = Stream.<String> builder().add("a").add("b").add("c").build();
|
||||
assertEquals(3, streamBuilder.count());
|
||||
|
||||
Stream<String> streamGenerated = Stream.generate(() -> "element").limit(10);
|
||||
assertEquals(10, streamGenerated.count());
|
||||
|
||||
Stream<Integer> streamIterated = Stream.iterate(40, n -> n + 2).limit(20);
|
||||
assertTrue(40 <= streamIterated.findAny().get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void runStreamPipeline_whenOrderIsRight_thenCorrect() {
|
||||
|
||||
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
|
||||
Optional<String> stream = list.stream().filter(element -> {
|
||||
log.info("filter() was called");
|
||||
return element.contains("2");
|
||||
}).map(element -> {
|
||||
log.info("map() was called");
|
||||
return element.toUpperCase();
|
||||
}).findFirst();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void reduce_whenExpected_thenCorrect() {
|
||||
|
||||
OptionalInt reduced = IntStream.range(1, 4).reduce((a, b) -> a + b);
|
||||
assertEquals(6, reduced.getAsInt());
|
||||
|
||||
int reducedTwoParams = IntStream.range(1, 4).reduce(10, (a, b) -> a + b);
|
||||
assertEquals(16, reducedTwoParams);
|
||||
|
||||
int reducedThreeParams = Stream.of(1, 2, 3).reduce(10, (a, b) -> a + b, (a, b) -> {
|
||||
log.info("combiner was called");
|
||||
return a + b;
|
||||
});
|
||||
assertEquals(16, reducedThreeParams);
|
||||
|
||||
int reducedThreeParamsParallel = Arrays.asList(1, 2, 3).parallelStream().reduce(10, (a, b) -> a + b, (a, b) -> {
|
||||
log.info("combiner was called");
|
||||
return a + b;
|
||||
});
|
||||
assertEquals(36, reducedThreeParamsParallel);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void collecting_whenAsExpected_thenCorrect() {
|
||||
|
||||
List<String> collectorCollection = productList.stream().map(Product::getName).collect(Collectors.toList());
|
||||
|
||||
assertTrue(collectorCollection instanceof List);
|
||||
assertEquals(5, collectorCollection.size());
|
||||
|
||||
String listToString = productList.stream().map(Product::getName).collect(Collectors.joining(", ", "[", "]"));
|
||||
|
||||
assertTrue(listToString.contains(",") && listToString.contains("[") && listToString.contains("]"));
|
||||
|
||||
double averagePrice = productList.stream().collect(Collectors.averagingInt(Product::getPrice));
|
||||
assertTrue(17.2 == averagePrice);
|
||||
|
||||
int summingPrice = productList.stream().collect(Collectors.summingInt(Product::getPrice));
|
||||
assertEquals(86, summingPrice);
|
||||
|
||||
IntSummaryStatistics statistics = productList.stream().collect(Collectors.summarizingInt(Product::getPrice));
|
||||
assertEquals(23, statistics.getMax());
|
||||
|
||||
Map<Integer, List<Product>> collectorMapOfLists = productList.stream().collect(Collectors.groupingBy(Product::getPrice));
|
||||
assertEquals(3, collectorMapOfLists.keySet().size());
|
||||
|
||||
Map<Boolean, List<Product>> mapPartioned = productList.stream().collect(Collectors.partitioningBy(element -> element.getPrice() > 15));
|
||||
assertEquals(2, mapPartioned.keySet().size());
|
||||
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void collect_whenThrows_thenCorrect() {
|
||||
Set<Product> unmodifiableSet = productList.stream().collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet));
|
||||
unmodifiableSet.add(new Product(4, "tea"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void customCollector_whenResultContainsAllElementsFrSource_thenCorrect() {
|
||||
Collector<Product, ?, LinkedList<Product>> toLinkedList = Collector.of(LinkedList::new, LinkedList::add, (first, second) -> {
|
||||
first.addAll(second);
|
||||
return first;
|
||||
});
|
||||
|
||||
LinkedList<Product> linkedListOfPersons = productList.stream().collect(toLinkedList);
|
||||
assertTrue(linkedListOfPersons.containsAll(productList));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parallelStream_whenWorks_thenCorrect() {
|
||||
Stream<Product> streamOfCollection = productList.parallelStream();
|
||||
boolean isParallel = streamOfCollection.isParallel();
|
||||
boolean haveBigPrice = streamOfCollection.map(product -> product.getPrice() * 12).anyMatch(price -> price > 200);
|
||||
assertTrue(isParallel && haveBigPrice);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parallel_whenIsParallel_thenCorrect() {
|
||||
IntStream intStreamParallel = IntStream.range(1, 150).parallel().map(element -> element * 34);
|
||||
boolean isParallel = intStreamParallel.isParallel();
|
||||
assertTrue(isParallel);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parallel_whenIsSequential_thenCorrect() {
|
||||
IntStream intStreamParallel = IntStream.range(1, 150).parallel().map(element -> element * 34);
|
||||
IntStream intStreamSequential = intStreamParallel.sequential();
|
||||
boolean isParallel = intStreamParallel.isParallel();
|
||||
assertFalse(isParallel);
|
||||
}
|
||||
|
||||
private Path getPath() {
|
||||
Path path = null;
|
||||
try {
|
||||
path = Files.createTempFile(null, ".txt");
|
||||
} catch (IOException e) {
|
||||
log.error(e.getMessage());
|
||||
}
|
||||
|
||||
try (BufferedWriter writer = Files.newBufferedWriter(path)) {
|
||||
writer.write("a\nb\nc");
|
||||
} catch (IOException e) {
|
||||
log.error(e.getMessage());
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
private void wasCalled() {
|
||||
counter++;
|
||||
}
|
||||
}
|
||||
-104
@@ -1,104 +0,0 @@
|
||||
package com.baeldung.streams;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class Java8StreamsUnitTest {
|
||||
|
||||
private List<String> list;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
list = new ArrayList<>();
|
||||
list.add("One");
|
||||
list.add("OneAndOnly");
|
||||
list.add("Derek");
|
||||
list.add("Change");
|
||||
list.add("factory");
|
||||
list.add("justBefore");
|
||||
list.add("Italy");
|
||||
list.add("Italy");
|
||||
list.add("Thursday");
|
||||
list.add("");
|
||||
list.add("");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkStreamCount_whenCreating_givenDifferentSources() {
|
||||
String[] arr = new String[] { "a", "b", "c" };
|
||||
Stream<String> streamArr = Arrays.stream(arr);
|
||||
assertEquals(streamArr.count(), 3);
|
||||
|
||||
Stream<String> streamOf = Stream.of("a", "b", "c");
|
||||
assertEquals(streamOf.count(), 3);
|
||||
|
||||
long count = list.stream().distinct().count();
|
||||
assertEquals(count, 9);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkStreamCount_whenOperationFilter_thanCorrect() {
|
||||
Stream<String> streamFilter = list.stream().filter(element -> element.isEmpty());
|
||||
assertEquals(streamFilter.count(), 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkStreamCount_whenOperationMap_thanCorrect() {
|
||||
List<String> uris = new ArrayList<>();
|
||||
uris.add("C:\\My.txt");
|
||||
Stream<Path> streamMap = uris.stream().map(uri -> Paths.get(uri));
|
||||
assertEquals(streamMap.count(), 1);
|
||||
|
||||
List<Detail> details = new ArrayList<>();
|
||||
details.add(new Detail());
|
||||
details.add(new Detail());
|
||||
Stream<String> streamFlatMap = details.stream().flatMap(detail -> detail.getParts().stream());
|
||||
assertEquals(streamFlatMap.count(), 4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkStreamCount_whenOperationMatch_thenCorrect() {
|
||||
boolean isValid = list.stream().anyMatch(element -> element.contains("h"));
|
||||
boolean isValidOne = list.stream().allMatch(element -> element.contains("h"));
|
||||
boolean isValidTwo = list.stream().noneMatch(element -> element.contains("h"));
|
||||
assertTrue(isValid);
|
||||
assertFalse(isValidOne);
|
||||
assertFalse(isValidTwo);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkStreamReducedValue_whenOperationReduce_thenCorrect() {
|
||||
List<Integer> integers = new ArrayList<>();
|
||||
integers.add(1);
|
||||
integers.add(1);
|
||||
integers.add(1);
|
||||
Integer reduced = integers.stream().reduce(23, (a, b) -> a + b);
|
||||
assertTrue(reduced == 26);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkStreamContains_whenOperationCollect_thenCorrect() {
|
||||
List<String> resultList = list.stream().map(element -> element.toUpperCase()).collect(Collectors.toList());
|
||||
assertEquals(resultList.size(), list.size());
|
||||
assertTrue(resultList.contains(""));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkParallelStream_whenDoWork() {
|
||||
list.parallelStream().forEach(element -> doWork(element));
|
||||
}
|
||||
|
||||
private void doWork(String string) {
|
||||
assertTrue(true); // just imitate an amount of work
|
||||
}
|
||||
}
|
||||
-118
@@ -1,118 +0,0 @@
|
||||
package com.baeldung.streams;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.StringWriter;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class PeekUnitTest {
|
||||
|
||||
private StringWriter out;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
out = new StringWriter();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringStream_whenCallingPeekOnly_thenNoElementProcessed() {
|
||||
// given
|
||||
Stream<String> nameStream = Stream.of("Alice", "Bob", "Chuck");
|
||||
|
||||
// when
|
||||
nameStream.peek(out::append);
|
||||
|
||||
// then
|
||||
assertThat(out.toString()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringStream_whenCallingForEachOnly_thenElementsProcessed() {
|
||||
// given
|
||||
Stream<String> nameStream = Stream.of("Alice", "Bob", "Chuck");
|
||||
|
||||
// when
|
||||
nameStream.forEach(out::append);
|
||||
|
||||
// then
|
||||
assertThat(out.toString()).isEqualTo("AliceBobChuck");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringStream_whenCallingPeekAndNoopForEach_thenElementsProcessed() {
|
||||
// given
|
||||
Stream<String> nameStream = Stream.of("Alice", "Bob", "Chuck");
|
||||
|
||||
// when
|
||||
nameStream.peek(out::append)
|
||||
.forEach(this::noop);
|
||||
|
||||
// then
|
||||
assertThat(out.toString()).isEqualTo("AliceBobChuck");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringStream_whenCallingPeekAndCollect_thenElementsProcessed() {
|
||||
// given
|
||||
Stream<String> nameStream = Stream.of("Alice", "Bob", "Chuck");
|
||||
|
||||
// when
|
||||
nameStream.peek(out::append)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// then
|
||||
assertThat(out.toString()).isEqualTo("AliceBobChuck");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringStream_whenCallingPeekAndForEach_thenElementsProcessedTwice() {
|
||||
// given
|
||||
Stream<String> nameStream = Stream.of("Alice", "Bob", "Chuck");
|
||||
|
||||
// when
|
||||
nameStream.peek(out::append)
|
||||
.forEach(out::append);
|
||||
|
||||
// then
|
||||
assertThat(out.toString()).isEqualTo("AliceAliceBobBobChuckChuck");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringStream_whenCallingPeek_thenElementsProcessedTwice() {
|
||||
// given
|
||||
Stream<User> userStream = Stream.of(new User("Alice"), new User("Bob"), new User("Chuck"));
|
||||
|
||||
// when
|
||||
userStream.peek(u -> u.setName(u.getName().toLowerCase()))
|
||||
.map(User::getName)
|
||||
.forEach(out::append);
|
||||
|
||||
// then
|
||||
assertThat(out.toString()).isEqualTo("alicebobchuck");
|
||||
}
|
||||
|
||||
private static class User {
|
||||
private String name;
|
||||
|
||||
public User(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void noop(String s) {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
package com.baeldung.streams;
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
-48
@@ -1,48 +0,0 @@
|
||||
package com.baeldung.streams;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class StreamAddUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenStream_whenAppendingObject_thenAppended() {
|
||||
Stream<String> anStream = Stream.of("a", "b", "c", "d", "e");
|
||||
|
||||
Stream<String> newStream = Stream.concat(anStream, Stream.of("A"));
|
||||
|
||||
List<String> resultList = newStream.collect(Collectors.toList());
|
||||
assertEquals(resultList.get(resultList.size() - 1), "A");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStream_whenPrependingObject_thenPrepended() {
|
||||
Stream<Integer> anStream = Stream.of(1, 2, 3, 4, 5);
|
||||
|
||||
Stream<Integer> newStream = Stream.concat(Stream.of(99), anStream);
|
||||
|
||||
assertEquals(newStream.findFirst()
|
||||
.get(), (Integer) 99);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStream_whenInsertingObject_thenInserted() {
|
||||
Stream<Double> anStream = Stream.of(1.1, 2.2, 3.3);
|
||||
|
||||
Stream<Double> newStream = insertInStream(anStream, 9.9, 3);
|
||||
|
||||
List<Double> resultList = newStream.collect(Collectors.toList());
|
||||
assertEquals(resultList.get(3), (Double) 9.9);
|
||||
}
|
||||
|
||||
private <T> Stream<T> insertInStream(Stream<T> stream, T elem, int index) {
|
||||
List<T> result = stream.collect(Collectors.toList());
|
||||
result.add(index, elem);
|
||||
return result.stream();
|
||||
}
|
||||
}
|
||||
-80
@@ -1,80 +0,0 @@
|
||||
package com.baeldung.streams;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class StreamMapUnitTest {
|
||||
|
||||
private Map<String, String> books;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
books = new HashMap<>();
|
||||
books.put("978-0201633610", "Design patterns : elements of reusable object-oriented software");
|
||||
books.put("978-1617291999", "Java 8 in Action: Lambdas, Streams, and functional-style programming");
|
||||
books.put("978-0134685991", "Effective Java");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void whenOptionalVersionCalledForExistingTitle_thenReturnOptionalWithISBN() {
|
||||
Optional<String> optionalIsbn = books.entrySet().stream()
|
||||
.filter(e -> "Effective Java".equals(e.getValue()))
|
||||
.map(Map.Entry::getKey).findFirst();
|
||||
|
||||
assertEquals("978-0134685991", optionalIsbn.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenOptionalVersionCalledForNonExistingTitle_thenReturnEmptyOptionalForISBN() {
|
||||
Optional<String> optionalIsbn = books.entrySet().stream()
|
||||
.filter(e -> "Non Existent Title".equals(e.getValue()))
|
||||
.map(Map.Entry::getKey).findFirst();
|
||||
|
||||
assertEquals(false, optionalIsbn.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMultipleResultsVersionCalledForExistingTitle_aCollectionWithMultipleValuesIsReturned() {
|
||||
books.put("978-0321356680", "Effective Java: Second Edition");
|
||||
|
||||
List<String> isbnCodes = books.entrySet().stream()
|
||||
.filter(e -> e.getValue().startsWith("Effective Java"))
|
||||
.map(Map.Entry::getKey)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertTrue(isbnCodes.contains("978-0321356680"));
|
||||
assertTrue(isbnCodes.contains("978-0134685991"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMultipleResultsVersionCalledForNonExistingTitle_aCollectionWithNoValuesIsReturned() {
|
||||
List<String> isbnCodes = books.entrySet().stream()
|
||||
.filter(e -> e.getValue().startsWith("Spring"))
|
||||
.map(Map.Entry::getKey)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertTrue(isbnCodes.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenKeysFollowingPatternReturnsAllValuesForThoseKeys() {
|
||||
List<String> titlesForKeyPattern = books.entrySet().stream()
|
||||
.filter(e -> e.getKey().startsWith("978-0"))
|
||||
.map(Map.Entry::getValue)
|
||||
.collect(Collectors.toList());
|
||||
assertEquals(2, titlesForKeyPattern.size());
|
||||
assertTrue(titlesForKeyPattern.contains("Design patterns : elements of reusable object-oriented software"));
|
||||
assertTrue(titlesForKeyPattern.contains("Effective Java"));
|
||||
}
|
||||
|
||||
}
|
||||
-57
@@ -1,57 +0,0 @@
|
||||
package com.baeldung.streams;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static java.util.stream.Collectors.*;
|
||||
|
||||
public class StreamToImmutableUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenUsingCollectingToImmutableSet_thenSuccess() {
|
||||
List<String> givenList = Arrays.asList("a", "b", "c");
|
||||
List<String> result = givenList.stream()
|
||||
.collect(collectingAndThen(toSet(), ImmutableList::copyOf));
|
||||
|
||||
System.out.println(result.getClass());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCollectingToUnmodifiableList_thenSuccess() {
|
||||
List<String> givenList = new ArrayList<>(Arrays.asList("a", "b", "c"));
|
||||
List<String> result = givenList.stream()
|
||||
.collect(collectingAndThen(toList(), Collections::unmodifiableList));
|
||||
|
||||
System.out.println(result.getClass());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectToImmutableList_thenSuccess() {
|
||||
List<Integer> list = IntStream.range(0, 9)
|
||||
.boxed()
|
||||
.collect(ImmutableList.toImmutableList());
|
||||
|
||||
System.out.println(list.getClass());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectToMyImmutableListCollector_thenSuccess() {
|
||||
List<String> givenList = Arrays.asList("a", "b", "c", "d");
|
||||
List<String> result = givenList.stream()
|
||||
.collect(MyImmutableListCollector.toImmutableList());
|
||||
|
||||
System.out.println(result.getClass());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPassingSupplier_thenSuccess() {
|
||||
List<String> givenList = Arrays.asList("a", "b", "c", "d");
|
||||
List<String> result = givenList.stream()
|
||||
.collect(MyImmutableListCollector.toImmutableList(LinkedList::new));
|
||||
|
||||
System.out.println(result.getClass());
|
||||
}
|
||||
}
|
||||
-80
@@ -1,80 +0,0 @@
|
||||
package com.baeldung.streams.removeitem;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class StreamOperateAndRemoveUnitTest {
|
||||
|
||||
private List<Item> itemList;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
|
||||
itemList = new ArrayList<>();
|
||||
for (int i = 0; i < 10; i++) {
|
||||
itemList.add(new Item(i));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOf10Items_whenFilteredForQualifiedItems_thenFilteredListContains5Items() {
|
||||
|
||||
final List<Item> filteredList = itemList.stream().filter(item -> item.isQualified())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
Assert.assertEquals(5, filteredList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOf10Items_whenOperateAndRemoveQualifiedItemsUsingRemoveIf_thenListContains5Items() {
|
||||
|
||||
final Predicate<Item> isQualified = item -> item.isQualified();
|
||||
itemList.stream().filter(isQualified).forEach(item -> item.operate());
|
||||
itemList.removeIf(isQualified);
|
||||
|
||||
Assert.assertEquals(5, itemList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOf10Items_whenOperateAndRemoveQualifiedItemsUsingRemoveAll_thenListContains5Items() {
|
||||
|
||||
final List<Item> operatedList = new ArrayList<>();
|
||||
itemList.stream().filter(item -> item.isQualified()).forEach(item -> {
|
||||
item.operate();
|
||||
operatedList.add(item);
|
||||
});
|
||||
itemList.removeAll(operatedList);
|
||||
|
||||
Assert.assertEquals(5, itemList.size());
|
||||
}
|
||||
|
||||
class Item {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(this.getClass().getName());
|
||||
|
||||
private final int value;
|
||||
|
||||
public Item(final int value) {
|
||||
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public boolean isQualified() {
|
||||
|
||||
return value % 2 == 0;
|
||||
}
|
||||
|
||||
public void operate() {
|
||||
|
||||
logger.info("Even Number: " + this.value);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
## Core Java streams
|
||||
|
||||
This module contains articles about the Stream API in Java.
|
||||
|
||||
### Relevant Articles:
|
||||
- [The Difference Between map() and flatMap()](https://www.baeldung.com/java-difference-map-and-flatmap)
|
||||
- [How to Use if/else Logic in Java 8 Streams](https://www.baeldung.com/java-8-streams-if-else-logic)
|
||||
- [The Difference Between Collection.stream().forEach() and Collection.forEach()](https://www.baeldung.com/java-collection-stream-foreach)
|
||||
- [Primitive Type Streams in Java 8](https://www.baeldung.com/java-8-primitive-streams)
|
||||
- [Debugging Java 8 Streams with IntelliJ](https://www.baeldung.com/intellij-debugging-java-streams)
|
||||
- [Add BigDecimals using the Stream API](https://www.baeldung.com/java-stream-add-bigdecimals)
|
||||
- [Should We Close a Java Stream?](https://www.baeldung.com/java-stream-close)
|
||||
- [Returning Stream vs. Collection](https://www.baeldung.com/java-return-stream-collection)
|
||||
- [Convert a Java Enumeration Into a Stream](https://www.baeldung.com/java-enumeration-to-stream)
|
||||
- [When to Use a Parallel Stream in Java](https://www.baeldung.com/java-when-to-use-parallel-stream)
|
||||
- More articles: [[<-- prev>]](/../core-java-streams-2)
|
||||
@@ -1,73 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-streams-3</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-streams-3</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh-generator.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-streams-3</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
<annotationProcessorPaths>
|
||||
<path>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh-generator.version}</version>
|
||||
</path>
|
||||
</annotationProcessorPaths>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<lombok.version>1.18.20</lombok.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
-30
@@ -1,30 +0,0 @@
|
||||
package com.baeldung.streams.closure;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Arrays;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Contains a couple of simple stream API usages.
|
||||
*/
|
||||
public class StreamClosureSnippets {
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
// Collection based streams shouldn't be closed
|
||||
Arrays.asList("Red", "Blue", "Green")
|
||||
.stream()
|
||||
.filter(c -> c.length() > 4)
|
||||
.map(String::toUpperCase)
|
||||
.forEach(System.out::print);
|
||||
|
||||
String[] colors = {"Red", "Blue", "Green"};
|
||||
Arrays.stream(colors).map(String::toUpperCase).forEach(System.out::println);
|
||||
|
||||
// IO-Based Streams Should be Closed via Try with Resources
|
||||
try (Stream<String> lines = Files.lines(Paths.get("/path/tp/file"))) {
|
||||
// lines will be closed after exiting the try block
|
||||
}
|
||||
}
|
||||
}
|
||||
-30
@@ -1,30 +0,0 @@
|
||||
package com.baeldung.streams.conversion;
|
||||
|
||||
import java.util.Enumeration;
|
||||
import java.util.Spliterators.AbstractSpliterator;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class EnumerationSpliterator<T> extends AbstractSpliterator<T> {
|
||||
|
||||
private final Enumeration<T> enumeration;
|
||||
|
||||
public EnumerationSpliterator(long est, int additionalCharacteristics, Enumeration<T> enumeration) {
|
||||
super(est, additionalCharacteristics);
|
||||
this.enumeration = enumeration;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean tryAdvance(Consumer<? super T> action) {
|
||||
if (enumeration.hasMoreElements()) {
|
||||
action.accept(enumeration.nextElement());
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void forEachRemaining(Consumer<? super T> action) {
|
||||
while (enumeration.hasMoreElements())
|
||||
action.accept(enumeration.nextElement());
|
||||
}
|
||||
}
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
package com.baeldung.streams.conversion;
|
||||
|
||||
import java.util.Enumeration;
|
||||
import java.util.Spliterator;
|
||||
import java.util.stream.Stream;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
public class EnumerationStreamConversion {
|
||||
|
||||
public static <T> Stream<T> convert(Enumeration<T> enumeration) {
|
||||
EnumerationSpliterator<T> spliterator = new EnumerationSpliterator<T>(Long.MAX_VALUE, Spliterator.ORDERED, enumeration);
|
||||
Stream<T> stream = StreamSupport.stream(spliterator, false);
|
||||
|
||||
return stream;
|
||||
}
|
||||
}
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
package com.baeldung.streams.debug.entity;
|
||||
|
||||
public class Customer {
|
||||
private final String name;
|
||||
private final int age;
|
||||
|
||||
public Customer(String name, int age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
}
|
||||
-84
@@ -1,84 +0,0 @@
|
||||
package com.baeldung.streams.forEach;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
class ReverseList extends ArrayList<String> {
|
||||
|
||||
List<String> list = Arrays.asList("A", "B", "C", "D");
|
||||
|
||||
Consumer<String> removeElement = s -> {
|
||||
System.out.println(s + " " + list.size());
|
||||
if (s != null && s.equals("A")) {
|
||||
list.remove("D");
|
||||
}
|
||||
};
|
||||
|
||||
@Override
|
||||
public Iterator<String> iterator() {
|
||||
|
||||
final int startIndex = this.size() - 1;
|
||||
final List<String> list = this;
|
||||
return new Iterator<String>() {
|
||||
|
||||
int currentIndex = startIndex;
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return currentIndex >= 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String next() {
|
||||
String next = list.get(currentIndex);
|
||||
currentIndex--;
|
||||
return next;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public void forEach(Consumer<? super String> action) {
|
||||
for (String s : this) {
|
||||
action.accept(s);
|
||||
}
|
||||
}
|
||||
|
||||
public void iterateParallel() {
|
||||
list.forEach(System.out::print);
|
||||
System.out.print(" ");
|
||||
list.parallelStream().forEach(System.out::print);
|
||||
}
|
||||
|
||||
public void iterateReverse() {
|
||||
List<String> myList = new ReverseList();
|
||||
myList.addAll(list);
|
||||
myList.forEach(System.out::print);
|
||||
System.out.print(" ");
|
||||
myList.stream().forEach(System.out::print);
|
||||
}
|
||||
|
||||
public void removeInCollectionForEach() {
|
||||
list.forEach(removeElement);
|
||||
}
|
||||
|
||||
public void removeInStreamForEach() {
|
||||
list.stream().forEach(removeElement);
|
||||
}
|
||||
|
||||
public static void main(String[] argv) {
|
||||
|
||||
ReverseList collectionForEach = new ReverseList();
|
||||
collectionForEach.iterateParallel();
|
||||
collectionForEach.iterateReverse();
|
||||
collectionForEach.removeInCollectionForEach();
|
||||
collectionForEach.removeInStreamForEach();
|
||||
}
|
||||
}
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
package com.baeldung.streams.parallel;
|
||||
|
||||
public class BenchmarkRunner {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
org.openjdk.jmh.Main.main(args);
|
||||
}
|
||||
|
||||
}
|
||||
-54
@@ -1,54 +0,0 @@
|
||||
package com.baeldung.streams.parallel;
|
||||
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||
import org.openjdk.jmh.annotations.Mode;
|
||||
import org.openjdk.jmh.annotations.OutputTimeUnit;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class DifferentSourceSplitting {
|
||||
|
||||
private static final List<Integer> arrayListOfNumbers = new ArrayList<>();
|
||||
private static final List<Integer> linkedListOfNumbers = new LinkedList<>();
|
||||
|
||||
static {
|
||||
IntStream.rangeClosed(1, 1_000_000).forEach(i -> {
|
||||
arrayListOfNumbers.add(i);
|
||||
linkedListOfNumbers.add(i);
|
||||
});
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public static void differentSourceArrayListSequential() {
|
||||
arrayListOfNumbers.stream().reduce(0, Integer::sum);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public static void differentSourceArrayListParallel() {
|
||||
arrayListOfNumbers.parallelStream().reduce(0, Integer::sum);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public static void differentSourceLinkedListSequential() {
|
||||
linkedListOfNumbers.stream().reduce(0, Integer::sum);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public static void differentSourceLinkedListParallel() {
|
||||
linkedListOfNumbers.parallelStream().reduce(0, Integer::sum);
|
||||
}
|
||||
|
||||
}
|
||||
-52
@@ -1,52 +0,0 @@
|
||||
package com.baeldung.streams.parallel;
|
||||
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||
import org.openjdk.jmh.annotations.Mode;
|
||||
import org.openjdk.jmh.annotations.OutputTimeUnit;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class MemoryLocalityCosts {
|
||||
|
||||
private static final int[] intArray = new int[1_000_000];
|
||||
private static final Integer[] integerArray = new Integer[1_000_000];
|
||||
|
||||
static {
|
||||
IntStream.rangeClosed(1, 1_000_000).forEach(i -> {
|
||||
intArray[i-1] = i;
|
||||
integerArray[i-1] = i;
|
||||
});
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public static void localityIntArraySequential() {
|
||||
Arrays.stream(intArray).reduce(0, Integer::sum);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public static void localityIntArrayParallel() {
|
||||
Arrays.stream(intArray).parallel().reduce(0, Integer::sum);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public static void localityIntegerArraySequential() {
|
||||
Arrays.stream(integerArray).reduce(0, Integer::sum);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public static void localityIntegerArrayParallel() {
|
||||
Arrays.stream(integerArray).parallel().reduce(0, Integer::sum);
|
||||
}
|
||||
|
||||
}
|
||||
-52
@@ -1,52 +0,0 @@
|
||||
package com.baeldung.streams.parallel;
|
||||
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||
import org.openjdk.jmh.annotations.Mode;
|
||||
import org.openjdk.jmh.annotations.OutputTimeUnit;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class MergingCosts {
|
||||
|
||||
private static final List<Integer> arrayListOfNumbers = new ArrayList<>();
|
||||
|
||||
static {
|
||||
IntStream.rangeClosed(1, 1_000_000).forEach(i -> {
|
||||
arrayListOfNumbers.add(i);
|
||||
});
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public static void mergingCostsSumSequential() {
|
||||
arrayListOfNumbers.stream().reduce(0, Integer::sum);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public static void mergingCostsSumParallel() {
|
||||
arrayListOfNumbers.stream().parallel().reduce(0, Integer::sum);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public static void mergingCostsGroupingSequential() {
|
||||
arrayListOfNumbers.stream().collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public static void mergingCostsGroupingParallel() {
|
||||
arrayListOfNumbers.stream().parallel().collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
}
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
package com.baeldung.streams.parallel;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class ParallelStream {
|
||||
|
||||
public static void main(String[] args) {
|
||||
List<Integer> listOfNumbers = Arrays.asList(1, 2, 3, 4);
|
||||
listOfNumbers.parallelStream().forEach(number ->
|
||||
System.out.println(number + " " + Thread.currentThread().getName())
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
package com.baeldung.streams.parallel;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class SequentialStream {
|
||||
|
||||
public static void main(String[] args) {
|
||||
List<Integer> listOfNumbers = Arrays.asList(1, 2, 3, 4);
|
||||
listOfNumbers.stream().forEach(number ->
|
||||
System.out.println(number + " " + Thread.currentThread().getName())
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
-27
@@ -1,27 +0,0 @@
|
||||
package com.baeldung.streams.parallel;
|
||||
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||
import org.openjdk.jmh.annotations.Mode;
|
||||
import org.openjdk.jmh.annotations.OutputTimeUnit;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class SplittingCosts {
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public static void sourceSplittingIntStreamSequential() {
|
||||
IntStream.rangeClosed(1, 100).reduce(0, Integer::sum);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public static void sourceSplittingIntStreamParallel() {
|
||||
IntStream.rangeClosed(1, 100).parallel().reduce(0, Integer::sum);
|
||||
}
|
||||
|
||||
}
|
||||
-23
@@ -1,23 +0,0 @@
|
||||
package com.baeldung.streams.primitivestreams;
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
-95
@@ -1,95 +0,0 @@
|
||||
package com.baeldung.streams.streamvscollection;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.SortedSet;
|
||||
import java.util.TreeSet;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class StreamVsCollectionExample {
|
||||
|
||||
static ArrayList<String> userNameSource = new ArrayList<>();
|
||||
|
||||
static {
|
||||
userNameSource.add("john");
|
||||
userNameSource.add("smith");
|
||||
userNameSource.add("tom");
|
||||
userNameSource.add("rob");
|
||||
userNameSource.add("charlie");
|
||||
userNameSource.add("alfred");
|
||||
}
|
||||
|
||||
public static Stream<String> userNames() {
|
||||
return userNameSource.stream();
|
||||
}
|
||||
|
||||
public static List<String> userNameList() {
|
||||
return userNames().collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static Set<String> userNameSet() {
|
||||
return userNames().collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
public static Map<String, String> userNameMap() {
|
||||
return userNames().collect(Collectors.toMap(u1 -> u1.toString(), u1 -> u1.toString()));
|
||||
}
|
||||
|
||||
public static Stream<String> filterUserNames() {
|
||||
return userNames().filter(i -> i.length() >= 4);
|
||||
}
|
||||
|
||||
public static Stream<String> sortUserNames() {
|
||||
return userNames().sorted();
|
||||
}
|
||||
|
||||
public static Stream<String> limitUserNames() {
|
||||
return userNames().limit(3);
|
||||
}
|
||||
|
||||
public static Stream<String> sortFilterLimitUserNames() {
|
||||
return filterUserNames().sorted().limit(3);
|
||||
}
|
||||
|
||||
public static void printStream(Stream<String> stream) {
|
||||
stream.forEach(System.out::println);
|
||||
}
|
||||
|
||||
public static void modifyList() {
|
||||
userNameSource.remove(2);
|
||||
}
|
||||
|
||||
public static Map<String, String> modifyMap() {
|
||||
Map<String, String> userNameMap = userNameMap();
|
||||
userNameMap.put("bob", "bob");
|
||||
userNameMap.remove("alfred");
|
||||
|
||||
return userNameMap;
|
||||
}
|
||||
|
||||
public static void tryStreamTraversal() {
|
||||
Stream<String> userNameStream = userNames();
|
||||
userNameStream.forEach(System.out::println);
|
||||
|
||||
try {
|
||||
userNameStream.forEach(System.out::println);
|
||||
} catch(IllegalStateException e) {
|
||||
System.out.println("stream has already been operated upon or closed");
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println(userNameMap());
|
||||
System.out.println(modifyMap());
|
||||
tryStreamTraversal();
|
||||
|
||||
Set<String> set = userNames().collect(Collectors.toCollection(TreeSet::new));
|
||||
set.forEach(val -> System.out.println(val));
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
-42
@@ -1,42 +0,0 @@
|
||||
package com.baeldung.streams.bigdecimals;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class AddNumbersUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenIntStream_whenSum_thenResultIsCorrect() {
|
||||
IntStream intNumbers = IntStream.range(0, 3);
|
||||
assertEquals(3, intNumbers.sum());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCollectionOfDouble_whenUsingMapToDoubleToSum_thenResultIsCorrect() {
|
||||
List<Double> doubleNumbers = Arrays.asList(23.48, 52.26, 13.5);
|
||||
double result = doubleNumbers.stream()
|
||||
.mapToDouble(Double::doubleValue)
|
||||
.sum();
|
||||
assertEquals(89.24, result, .1);
|
||||
}
|
||||
|
||||
public void givenStreamOfIntegers_whenUsingReduceToSum_thenResultIsCorrect() {
|
||||
Stream<Integer> intNumbers = Stream.of(0, 1, 2);
|
||||
int result = intNumbers.reduce(0, Integer::sum);
|
||||
assertEquals(106, result);
|
||||
}
|
||||
|
||||
public void givenStreamOfBigDecimals_whenUsingReduceToSum_thenResultIsCorrect() {
|
||||
Stream<BigDecimal> bigDecimalNumber = Stream.of(BigDecimal.ZERO, BigDecimal.ONE, BigDecimal.TEN);
|
||||
BigDecimal result = bigDecimalNumber.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
assertEquals(11, result);
|
||||
}
|
||||
|
||||
}
|
||||
-41
@@ -1,41 +0,0 @@
|
||||
package com.baeldung.streams.conditional;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StreamForEachIfElseUnitTest {
|
||||
|
||||
@Test
|
||||
public final void givenIntegerStream_whenCheckingIntegerParityWithIfElse_thenEnsureCorrectParity() {
|
||||
List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
|
||||
|
||||
ints.stream()
|
||||
.forEach(i -> {
|
||||
if (i.intValue() % 2 == 0) {
|
||||
Assert.assertTrue(i.intValue() + " is not even", i.intValue() % 2 == 0);
|
||||
} else {
|
||||
Assert.assertTrue(i.intValue() + " is not odd", i.intValue() % 2 != 0);
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenIntegerStream_whenCheckingIntegerParityWithStreamFilter_thenEnsureCorrectParity() {
|
||||
List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
|
||||
|
||||
Stream<Integer> evenIntegers = ints.stream()
|
||||
.filter(i -> i.intValue() % 2 == 0);
|
||||
Stream<Integer> oddIntegers = ints.stream()
|
||||
.filter(i -> i.intValue() % 2 != 0);
|
||||
|
||||
evenIntegers.forEach(i -> Assert.assertTrue(i.intValue() + " is not even", i.intValue() % 2 == 0));
|
||||
oddIntegers.forEach(i -> Assert.assertTrue(i.intValue() + " is not odd", i.intValue() % 2 != 0));
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
package com.baeldung.streams.conversion;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Vector;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class EnumerationStreamConversionUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenEnumeration_whenConvertedToStream_thenNotNull() {
|
||||
Vector<Integer> input = new Vector<>(Arrays.asList(1, 2, 3, 4, 5));
|
||||
|
||||
Stream<Integer> resultingStream = EnumerationStreamConversion.convert(input.elements());
|
||||
|
||||
Assert.assertNotNull(resultingStream);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertedToList_thenCorrect() {
|
||||
Vector<Integer> input = new Vector<>(Arrays.asList(1, 2, 3, 4, 5));
|
||||
|
||||
Stream<Integer> stream = EnumerationStreamConversion.convert(input.elements());
|
||||
List<Integer> list = stream.filter(e -> e >= 3)
|
||||
.collect(Collectors.toList());
|
||||
assertThat(list, contains(3, 4, 5));
|
||||
}
|
||||
}
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
package com.baeldung.streams.debug;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class Example1 {
|
||||
@Test
|
||||
public void whenDebugging_thenInformationIsShown() {
|
||||
int[] listOutputSorted = IntStream.of(-3, 10, -4, 1, 3)
|
||||
.sorted()
|
||||
.toArray();
|
||||
|
||||
assertThat(listOutputSorted).isSorted();
|
||||
}
|
||||
}
|
||||
-36
@@ -1,36 +0,0 @@
|
||||
package com.baeldung.streams.debug;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.streams.debug.entity.Customer;
|
||||
|
||||
public class Example2 {
|
||||
@Test
|
||||
public void whenDebugging_thenInformationIsShown() {
|
||||
List<Optional<Customer>> customers = Arrays.asList(
|
||||
Optional.of(new Customer("John P.", 15)),
|
||||
Optional.of(new Customer("Sarah M.", 78)),
|
||||
Optional.empty(),
|
||||
Optional.of(new Customer("Mary T.", 20)),
|
||||
Optional.empty(),
|
||||
Optional.of(new Customer("Florian G.", 89)),
|
||||
Optional.empty()
|
||||
);
|
||||
|
||||
long numberOf65PlusCustomers = customers.stream()
|
||||
.flatMap(c -> c.map(Stream::of)
|
||||
.orElseGet(Stream::empty))
|
||||
.mapToInt(Customer::getAge)
|
||||
.filter(c -> c > 65)
|
||||
.count();
|
||||
|
||||
assertThat(numberOf65PlusCustomers).isEqualTo(2);
|
||||
}
|
||||
}
|
||||
-46
@@ -1,46 +0,0 @@
|
||||
package com.baeldung.streams.parallel;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ForkJoinPool;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class ForkJoinUnitTest {
|
||||
|
||||
@Test
|
||||
void givenSequentialStreamOfNumbers_whenReducingSumWithIdentityFive_thenResultIsCorrect() {
|
||||
List<Integer> listOfNumbers = Arrays.asList(1, 2, 3, 4);
|
||||
int sum = listOfNumbers.stream().reduce(5, Integer::sum);
|
||||
assertThat(sum).isEqualTo(15);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenParallelStreamOfNumbers_whenReducingSumWithIdentityFive_thenResultIsNotCorrect() {
|
||||
List<Integer> listOfNumbers = Arrays.asList(1, 2, 3, 4);
|
||||
int sum = listOfNumbers.parallelStream().reduce(5, Integer::sum);
|
||||
assertThat(sum).isNotEqualTo(15);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenParallelStreamOfNumbers_whenReducingSumWithIdentityZero_thenResultIsCorrect() {
|
||||
List<Integer> listOfNumbers = Arrays.asList(1, 2, 3, 4);
|
||||
int sum = listOfNumbers.parallelStream().reduce(0, Integer::sum) + 5;
|
||||
assertThat(sum).isEqualTo(15);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenParallelStreamOfNumbers_whenUsingCustomThreadPool_thenResultIsCorrect()
|
||||
throws InterruptedException, ExecutionException {
|
||||
List<Integer> listOfNumbers = Arrays.asList(1, 2, 3, 4);
|
||||
ForkJoinPool customThreadPool = new ForkJoinPool(4);
|
||||
int sum = customThreadPool.submit(
|
||||
() -> listOfNumbers.parallelStream().reduce(0, Integer::sum)).get();
|
||||
customThreadPool.shutdown();
|
||||
assertThat(sum).isEqualTo(10);
|
||||
}
|
||||
|
||||
}
|
||||
-93
@@ -1,93 +0,0 @@
|
||||
package com.baeldung.streams.primitivestreams;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class PrimitiveStreamsUnitTest {
|
||||
|
||||
private PrimitiveStreams streams = new PrimitiveStreams();
|
||||
|
||||
@Test
|
||||
public void givenAnArrayOfIntegersWhenMinIsCalledThenCorrectMinIsReturned() {
|
||||
int[] integers = new int[] { 20, 98, 12, 7, 35 };
|
||||
int min = streams.min(integers); // returns 7
|
||||
|
||||
assertEquals(7, min);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnArrayOfIntegersWhenMaxIsCalledThenCorrectMaxIsReturned() {
|
||||
int max = streams.max(20, 98, 12, 7, 35);
|
||||
|
||||
assertEquals(98, max);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnArrayOfIntegersWhenSumIsCalledThenCorrectSumIsReturned() {
|
||||
int sum = streams.sum(20, 98, 12, 7, 35);
|
||||
|
||||
assertEquals(172, sum);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnArrayOfIntegersWhenAvgIsCalledThenCorrectAvgIsReturned() {
|
||||
double avg = streams.avg(20, 98, 12, 7, 35);
|
||||
|
||||
assertTrue(34.4 == avg);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenARangeOfIntegersWhenIntStreamSumIsCalledThenCorrectSumIsReturned() {
|
||||
int sum = IntStream.range(1, 10).sum();
|
||||
|
||||
assertEquals(45, sum);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenARangeClosedOfIntegersWhenIntStreamSumIsCalledThenCorrectSumIsReturned() {
|
||||
int sum = IntStream.rangeClosed(1, 10).sum();
|
||||
|
||||
assertEquals(55, sum);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenARangeWhenForEachIsCalledThenTheIndicesWillBePrinted() {
|
||||
IntStream.rangeClosed(1, 5).parallel().forEach(System.out::println);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnArrayWhenSumIsCalledThenTheCorrectSumIsReturned() {
|
||||
|
||||
int sum = Stream.of(33, 45).mapToInt(i -> i).sum();
|
||||
|
||||
assertEquals(78, sum);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnIntStreamThenGetTheEvenIntegers() {
|
||||
List<Integer> evenInts = IntStream.rangeClosed(1, 10).filter(i -> i % 2 == 0).boxed().collect(Collectors.toList());
|
||||
|
||||
List<Integer> expected = IntStream.of(2, 4, 6, 8, 10).boxed().collect(Collectors.toList());
|
||||
|
||||
assertEquals(expected, evenInts);
|
||||
}
|
||||
|
||||
class Person {
|
||||
private int age;
|
||||
|
||||
Person(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
int getAge() {
|
||||
return age;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
## Relevant Articles:
|
||||
|
||||
- [Count Occurrences Using Java groupingBy Collector](https://www.baeldung.com/java-groupingby-count)
|
||||
@@ -1,61 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-streams-4</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-streams-4</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit</groupId>
|
||||
<artifactId>junit-bom</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-streams-4</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
<compilerArgument>-parameters</compilerArgument>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- testing -->
|
||||
<maven-compiler-plugin.version>3.1</maven-compiler-plugin.version>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
-84
@@ -1,84 +0,0 @@
|
||||
package com.baeldung.streamcollectors;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StreamGroupingByCollectorUnitTest {
|
||||
@Test
|
||||
public void givenListOfStrings_whenGroupingEqualStrings_thenUseCollectorsGroupingByToGroupEqualStringsAndCountOfOccurrences() {
|
||||
|
||||
List<String> list = new ArrayList<>(Arrays.asList("Foo", "Bar", "Bar", "Foo", "Bar"));
|
||||
|
||||
Map<String, Long> result = list.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
|
||||
Assert.assertEquals(new Long(2), result.get("Foo"));
|
||||
Assert.assertEquals(new Long(3), result.get("Bar"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfStrings_whenGroupingEqualLengthStrings_thenUseCollectorsGroupingByConcurrentToGroupEqualLengthStringsAndCountOfOccurrences() {
|
||||
|
||||
List<String> list = new ArrayList<>(Arrays.asList("Adam", "Bill", "Jack", "Joe", "Ian"));
|
||||
|
||||
Map<Integer, Long> result = list.stream().collect(Collectors.groupingByConcurrent(String::length, Collectors.counting()));
|
||||
Assert.assertEquals(new Long(2), result.get(3));
|
||||
Assert.assertEquals(new Long(3), result.get(4));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfEmployees_whenGroupingDepartmentId_thenUseCollectorsGroupingByDepartmentIdAndCountNumberOfEmployeesWithinEveryDepartment() {
|
||||
|
||||
List<Employee> list = new ArrayList<>(Arrays.asList(new Employee(1, "Joe", 1), new Employee(2, "Josh", 1), new Employee(3, "Jamie", 2), new Employee(4, "Jim", 2), new Employee(5, "Jack", 2)));
|
||||
|
||||
Map<Integer, Long> result = list.stream().collect(Collectors.groupingBy(Employee::getDepartmentId, Collectors.counting()));
|
||||
Assert.assertEquals(new Long(2), result.get(1));
|
||||
Assert.assertEquals(new Long(3), result.get(2));
|
||||
|
||||
}
|
||||
|
||||
static class Employee {
|
||||
|
||||
Integer employeeId;
|
||||
String employeeName;
|
||||
Integer departmentId;
|
||||
|
||||
Employee(Integer employeeId, String employeeName, Integer departmentId) {
|
||||
this.employeeId = employeeId;
|
||||
this.employeeName = employeeName;
|
||||
this.departmentId = departmentId;
|
||||
}
|
||||
|
||||
public Integer getEmployeeId() {
|
||||
return employeeId;
|
||||
}
|
||||
|
||||
public void setEmployeeId(Integer employeeId) {
|
||||
this.employeeId = employeeId;
|
||||
}
|
||||
|
||||
public String getEmployeeName() {
|
||||
return employeeName;
|
||||
}
|
||||
|
||||
public void setEmployeeName(String employeeName) {
|
||||
this.employeeName = employeeName;
|
||||
}
|
||||
|
||||
public Integer getDepartmentId() {
|
||||
return departmentId;
|
||||
}
|
||||
|
||||
public void setDepartmentId(Integer departmentId) {
|
||||
this.departmentId = departmentId;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -35,7 +35,7 @@
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
<version>${version.log4j}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
|
||||
@@ -10,8 +10,8 @@
|
||||
- [Java Localization – Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting)
|
||||
- [Java – Generate Random String](https://www.baeldung.com/java-random-string)
|
||||
- [Java String Interview Questions and Answers](https://www.baeldung.com/java-string-interview-questions)
|
||||
- [Java Multi-line String](https://www.baeldung.com/java-multiline-string)
|
||||
- [Java 多行字符串](https://www.ossez.com/t/java/14049)
|
||||
- [Java 中的 String Pool 简介](https://www.ossez.com/t/java-string-pool/14017)
|
||||
- [Fixing “constant string too long” Build Error](https://www.baeldung.com/java-constant-string-too-long-error)
|
||||
- [Java “constant string too long” 编译错误](https://www.ossez.com/t/java-constant-string-too-long/14048)
|
||||
- [Java 对象如何安全的 toString](https://www.ossez.com/t/java-tostring/14000)
|
||||
- [编程常用的几种字符编码](https://www.ossez.com/t/topic/14022)
|
||||
|
||||
+9
-4
@@ -2,14 +2,13 @@ package com.ossez.multiline;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.swing.*;
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class MultiLineStringUnitTest {
|
||||
|
||||
|
||||
|
||||
@Test
|
||||
public void whenCompareMultiLineStrings_thenTheyAreAllTheSame() throws IOException {
|
||||
MultiLineString ms = new MultiLineString();
|
||||
@@ -17,7 +16,13 @@ public class MultiLineStringUnitTest {
|
||||
assertEquals(ms.stringJoin(), ms.stringBuilder());
|
||||
assertEquals(ms.stringBuilder(), ms.guavaJoiner());
|
||||
assertEquals(ms.guavaJoiner(), ms.loadFromFile());
|
||||
assertEquals(ms.loadFromFile(), ms.textBlocks());
|
||||
|
||||
// Due to JDK version, we cannot test TestBlocks
|
||||
// assertEquals(ms.loadFromFile(), ms.textBlocks());
|
||||
}
|
||||
@Test
|
||||
public void newlineInOS() throws IOException {
|
||||
System.out.println(System.lineSeparator());
|
||||
System.out.println(System.getProperty("line.separator"));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
*.class
|
||||
|
||||
0.*
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
.resourceCache
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
|
||||
# Files generated by integration tests
|
||||
*.txt
|
||||
backup-pom.xml
|
||||
/bin/
|
||||
/temp
|
||||
|
||||
#IntelliJ specific
|
||||
.idea/
|
||||
*.iml
|
||||
@@ -0,0 +1,6 @@
|
||||
## Java 核心
|
||||
|
||||
本模块中包含有关 Java 核心新增功能特性的一些文章。
|
||||
|
||||
### 相关文章:
|
||||
- [Java Preview Features](https://www.baeldung.com/java-preview-features)
|
||||
@@ -0,0 +1,54 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java</artifactId>
|
||||
<name>core-java</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.ossez.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.2-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-8</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- util -->
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.ossez.features;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
|
||||
public class Template {
|
||||
|
||||
private static final Clock clock = Clock.fixed(Instant.parse("2016-10-09T15:10:30.00Z"), ZoneId.of("UTC"));
|
||||
|
||||
}
|
||||
+2
-2
@@ -2,12 +2,12 @@
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<root level="TRACE">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.ossez.features.util;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.temporal.ChronoField;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class CurrentDateTimeUnitTest {
|
||||
|
||||
private static final Clock clock = Clock.fixed(Instant.parse("2016-10-09T15:10:30.00Z"), ZoneId.of("UTC"));
|
||||
|
||||
@Test
|
||||
public void shouldReturnCurrentDate() {
|
||||
final LocalDate now = LocalDate.now(clock);
|
||||
|
||||
assertEquals(9, now.get(ChronoField.DAY_OF_MONTH));
|
||||
assertEquals(10, now.get(ChronoField.MONTH_OF_YEAR));
|
||||
assertEquals(2016, now.get(ChronoField.YEAR));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnCurrentTime() {
|
||||
final LocalTime now = LocalTime.now(clock);
|
||||
|
||||
assertEquals(15, now.get(ChronoField.HOUR_OF_DAY));
|
||||
assertEquals(10, now.get(ChronoField.MINUTE_OF_HOUR));
|
||||
assertEquals(30, now.get(ChronoField.SECOND_OF_MINUTE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnCurrentTimestamp() {
|
||||
final Instant now = Instant.now(clock);
|
||||
|
||||
assertEquals(clock.instant().getEpochSecond(), now.getEpochSecond());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user