我对字符串应用了 gzip 压缩test-string。当我将 Scala 2.13.8 与Java 11.0.13(Java HotSpot(TM) 64 位服务器 VM)一起使用时,会产生压缩字符串H4sIAAAAAAAAACtJLS7RLS4pysxLBwCFdJByCwAAAA==.
然而,当我在Java 17.0.4.1(OpenJDK 64 位服务器 VM)上使用 Scala 2.13.8 执行相同的压缩操作时,它会产生H4sIAAAAAAAA/ytJLS7RLS4pysxLBwCFdJByCwAAAA==.,这两个压缩字符串都正确解压缩以检索原始 string test-string。
我认为这可能取决于默认压缩级别等几个因素:Java 11 和 Java 17 之间的默认压缩级别可能有所不同,从而导致同一输入产生不同的输出。算法改进:Java 17 中的 Gzip 实现可能已经过优化,导致压缩结果不同。 内部实现细节:Gzip 压缩的内部实现细节在 Java 11 和 Java 17 之间可能发生了变化,影响了压缩输出。
这背后的原因可能是什么?我附上下面的代码。
val bos = new ByteArrayOutputStream("test-string".length)
val b64os = new Base64OutputStream(bos)
val gzip = new GZIPOutputStream(b64os)
gzip.write("test-string".getBytes("UTF-8"))
gzip.close()
val compressed = new String(bos.toByteArray, "UTF-8")
bos.close()
compressed.trim
Run Code Online (Sandbox Code Playgroud) Boolean我有一个看起来像这样的字段列表:
var lst = List.of(true, false, false, false);
Run Code Online (Sandbox Code Playgroud)
有一个这样的对象:
public class GetBatchStatusResponse {
String batchCompleted;
Integer totalCount;
Integer processed;
Integer pending;
}
Run Code Online (Sandbox Code Playgroud)
上面的对象当前填充有如下内容:
var resp = new GetBatchStatusResponse();
resp.setBatchCompleted(String.valueOf( !lst.contains(false));
resp.setTotalCount(lst.size());
resp.setProcessed((int)(lst.stream().filter(p ->p!=null && p == true).count()));
resp.setPending((int)(lst.stream().filter(p ->p==null || p == false).count()));
Run Code Online (Sandbox Code Playgroud)
如何在单个循环中使用流 API 实现同样的效果?
我正在使用 IntelliJ 和OpenJDK 17创建 JavaFX 应用程序。项目语言级别设置为17。创建 JAR(构建工件)后,我尝试使用JRE 1.8.0_311执行它。当我这样做时,我收到此错误:
java.lang.UnsupportedClassVersionError: Main has been compiled by a more recent version of the Java Runtime (class file version 61.0), this version of the Java Runtime only recognizes class file versions up to 52.0
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:756)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:473)
at java.net.URLClassLoader.access$100(URLClassLoader.java:74)
at java.net.URLClassLoader$1.run(URLClassLoader.java:369)
at java.net.URLClassLoader$1.run(URLClassLoader.java:363)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:362)
at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352)
at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:601)
Error: A JNI error has occurred, please …Run Code Online (Sandbox Code Playgroud) 我编写这段代码来找到最年轻的人:
import java.util.Comparator;
import java.util.List;
public class PersonImpl implements PersonInterface {
@Override
public Person youngest(List<Person> personList) {
Integer minAge = personList.stream()
.map(Person::getAge)
.min(Comparator.comparing(Integer::valueOf))
.orElse(null);
return personList.stream()
.filter(person -> person.getAge() == minAge)
.toList()
.stream()
.findFirst()
.orElse(null);
}
}
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,我做到了并且工作正常。现在我想知道我是否可以以更好的方式做到这一点(也许不是只对一个执行 2 个“语句”?) PS:我只提供了代码,因为我认为不需要发布所有的这里的其他课程只是为了回顾这一课程。
有人可以解释一下如何才能拥有更好的代码(更少的行)吗?谢谢
我遇到一个特定的用例,如果对象为空,我经常需要将它们包装起来Optional。看一下这段代码:
List<AbstractCorporateAction> cas = stream.toList();
if (cas.isEmpty()) return Optional.empty();
else return Optional.of(cas);
Run Code Online (Sandbox Code Playgroud)
我检查列表是否为空,如果确实为空,则返回一个空可选,如果不是,则将其包装。原因是有时我得到列表本身的空值,有时我得到一个实际的列表,但它是空的。
通过这种方法,当返回的可选本身为空时,我不需要仔细检查底层列表。
但对于不同的数据结构,实现方式有所不同。是否有第三方库的内置方法可以实现此目的?我得到的最接近的是 fromGuava.MoreObjects#isEmpty但它只检查对象是否为空,并且在它为空的情况下不返回可选值。
我可以为此编写自己的封面,但我正在寻找一种专业、可靠的方法来实现所需的功能。
如何在 Java 17(或类似版本)中创建数组或函数列表?
预期的假设用途:
var myListOfFunctions = List.of(this::myFunction, MyClass::someOtherFunction);
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
对象不是函数式接口
我打算流式传输这些函数并向它们传递相同的数据。
下面的代码片段
Instant.parse("2023-08-08T00:00:00+02:00")
Run Code Online (Sandbox Code Playgroud)
按照 java-17 中的预期进行编译和执行。但是用java-8执行时,抛出以下异常
java.time.format.DateTimeParseException: Text '2023-08-01T00:00:00+02:00' could not be parsed at index 19
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.Instant.parse(Instant.java:395)
...
Run Code Online (Sandbox Code Playgroud)
我的问题是为什么?java.time api 有什么变化吗?
请注意,我确实知道解决此问题的方法,以下代码适用于 java-8
OffsetDateTime.parse("2023-08-01T00:00:00+02:00", DateTimeFormatter.ISO_OFFSET_DATE_TIME).toInstant()
Run Code Online (Sandbox Code Playgroud)
它产生了期望的结果。我有兴趣知道在 java-time api 实现中,行为是否已经改变?
尝试使用示例代码来检查recordequals()与classhashCode()的默认行为,但与class相比,记录的行为似乎有所不同。
这是记录和类的代码示例
public class EqualsAndHashcode {
public static void main(String[] args) {
var employeeA = new Employee(101);
var employeeB = new Employee(101);
var employeeAClass = new EmployeeClass(102);
var employeeBClass = new EmployeeClass(102);
var printStream = System.out;
printStream.println("record equals: " + employeeA.equals(employeeB) + "\nhashcode objA: " + employeeA.hashCode() + "\nhashcode objB: " + employeeB.hashCode());
printStream.println("\nclass equals: " + employeeAClass.equals(employeeBClass) + "\nhashcode objA: " + employeeAClass.hashCode() + "\nhashcode objB: …Run Code Online (Sandbox Code Playgroud) 我将以下遗留代码迁移到 Java 16,但是由于这个新版本引入了强封装,它不起作用:
try {
Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
method.setAccessible(true);
method.invoke(new URLClassLoader(
new URL[] {}),
new File("C:/external-folder/my.jar").toURI().toURL()
);
} catch (Exception exc) {
exc.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
有办法让它发挥作用吗?
我正在开发一个具有接口I和类A并B实现它的 Java 程序。我还有另一个类实现C ,它有 2 个带有一个参数的方法:一个接受 A 的对象,另一个接受 B 的对象。
interface I {}
static class A implements I {}
static class B implements I {}
interface C {
String map(A a);
String map(B b);
}
public static void main(String[] args) {
// Injected at runtime;
C mapper = getInstance();
I a = new A();
I b = new B();
// This fail at compilation
String result = mapper.map(a);
}
private static C getInstance() …Run Code Online (Sandbox Code Playgroud) 我使用时的性能list.parallelStream()比使用时差得多list.stream()。您认为为什么会发生这种情况?顺便说一句,这是Java 17,我的CPU 是桌面级的 i5。
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.time.chrono.ChronoPeriod;
import java.time.chrono.HijrahChronology;
import java.time.chrono.HijrahDate;
import java.time.chrono.IsoChronology;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class App {
public static void main(String[] args) throws Exception {
int size = 1;
List<Integer> list = null;
long startTimeN;
long endTimeN;
long startTimeP;
long endTimeP;
long normalStreamCheckedSize;
long normalStreamTime;
long parallelStreamCheckedSize;
long parallelStreamTime; …Run Code Online (Sandbox Code Playgroud) java ×12
java-17 ×12
java-stream ×4
java-8 ×2
concurrency ×1
equals ×1
guava ×1
gzip ×1
hashcode ×1
java-16 ×1
java-record ×1
java-time ×1
javafx ×1
list ×1
oop ×1
option-type ×1
overloading ×1
reflection ×1
scala ×1
strictfp ×1