标签: java-8

sun.nio.ch.FileChannelImpl 中的 System.gc() 调用是一个坏情况吗?

try {
    // If no exception was thrown from map0, the address is valid
    addr = map0(imode, mapPosition, mapSize);
} catch (OutOfMemoryError x) {
    // An OutOfMemoryError may indicate that we've exhausted memory
    // so force gc and re-attempt map
    System.gc();
    try {
        Thread.sleep(100);
    } catch (InterruptedException y) {
        Thread.currentThread().interrupt();
    }
    try {
        addr = map0(imode, mapPosition, mapSize);
    } catch (OutOfMemoryError y) {
        // After a second OOME, fail
        throw new IOException("Map failed", y);
    }
}
Run Code Online (Sandbox Code Playgroud)

来自jdk8-b120 的 jdk/FileChannelImpl.java …

java garbage-collection java-8

3
推荐指数
1
解决办法
116
查看次数

java 流是否能够从映射/过滤条件中延迟减少?

我正在使用函数式编程风格来解决 Leetcode 的简单问题,计算一致字符串的数量。这个问题的前提很简单:计算谓词“所有值都在另一个集合中”成立的值的数量。

我有两种方法,一种我相当确定其行为符合我的要求,另一种我不太确定。两者都会产生正确的输出,但理想情况下,它们会在输出处于最终状态后停止评估其他元素。


    public int countConsistentStrings(String allowed, String[] words) {
        final Set<Character> set = allowed.chars()
          .mapToObj(c -> (char)c)
          .collect(Collectors.toCollection(HashSet::new));
        return (int)Arrays.stream(words)
          .filter(word ->
                  word.chars()
                  .allMatch(c -> set.contains((char)c))
                 )
          .count();
    }
Run Code Online (Sandbox Code Playgroud)

在此解决方案中,据我所知,allMatch 语句将在谓词不成立的 c 的第一个实例处终止并计算为 false,从而跳过该流中的其他值。


    public int countConsistentStrings(String allowed, String[] words) {
        Set<Character> set = allowed.chars()
          .mapToObj(c -> (char)c)
          .collect(Collectors.toCollection(HashSet::new));
        return (int)Arrays.stream(words)
          .filter(word ->
                  word.chars()
                  .mapToObj(c -> set.contains((char)c))
                  .reduce((a,b) -> a&&b)
                  .orElse(false)
                 )
          .count();
    }
Run Code Online (Sandbox Code Playgroud)

在此解决方案中,使用相同的逻辑,但allMatch我使用的map是 and then ,而不是reduce。从逻辑上讲,在单个false值来自 …

java lazy-evaluation java-8 java-stream

3
推荐指数
1
解决办法
691
查看次数

groupingBy 使用布尔值,但添加自定义字符串作为键

我有下面的代码并基于布尔值进行 groupingBy

Map<Boolean, List<Test>> products = testList
        .stream()
        .collect(Collectors.groupingBy(Test::isValidUser));
        
Run Code Online (Sandbox Code Playgroud)

我想把它收集起来Map<String, List<Test>

基于布尔值,想要将自定义键添加为“有效”和“无效”。

如果为isValidUsertrue,则要将密钥添加为“有效”,否则密钥应为“无效”

在 Java 11 中是否有可能做到这一点?

注意:没有在Test类中添加String变量

java collections java-8 java-stream collectors

3
推荐指数
1
解决办法
738
查看次数

DateTime("2019-08-07T19:20-5:00") 转换为带有偏移值的本地日期时间

我从源系统获取以下字符串格式的日期时间内容以及偏移时间值。

2019-08-07T19:20-5:00
Run Code Online (Sandbox Code Playgroud)

我想使用偏移值将其转换为日期时间。我尝试了以下方法,但没有得到预期的结果。

OffsetDateTime sourceDateTime = OffsetDateTime.parse("2019-08-07T19:20-5:00"); 
System.out.println(sourceDateTime.getOffset());
Run Code Online (Sandbox Code Playgroud)

输出

Exception in thread "main" java.time.format.DateTimeParseException: Text '2019-08-07T19:20-5:00' could not be parsed at index 16
    at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2046)
    at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
    at java.base/java.time.OffsetDateTime.parse(OffsetDateTime.java:402)
    at java.base/java.time.OffsetDateTime.parse(OffsetDateTime.java:387)
    at com.example.demo.Testfile.main(Testfile.java:19)
Run Code Online (Sandbox Code Playgroud)

有什么简单的方法可以达到预期的输出吗?

注意:我使用的是Java 8

java java-8 java-time

3
推荐指数
1
解决办法
231
查看次数

运行 React Native 应用程序时无法识别的 VM 选项“MaxPermSize=512m”且无法创建 Java 虚拟机(已关闭)

我尝试使用此命令运行反应本机应用程序。

npx react-native run-android --variant=stagingDebug --appId com.xx_staging
Run Code Online (Sandbox Code Playgroud)

但我收到此错误消息。我想在我的机器上运行多个java版本。我怎样才能做到这一点?我也不想更改MaxPermSize=512m。我想保持MaxPermSize=512m不变。

npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.
info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.
Jetifier found 2228 file(s) to forward-jetify. Using 4 workers...
info Starting JS server...
'"adb"' is not recognized as an internal or external command,
operable program or batch file.
info Launching emulator...
error Failed to launch emulator. Reason: No emulators found …
Run Code Online (Sandbox Code Playgroud)

java java-7 java-8 java-11

3
推荐指数
1
解决办法
1万
查看次数

dateTimeFormatter 短时区名称未返回

java8中的以下代码没有返回短时区名称,而是返回“-08:00”

ZonedDateTime dateTime1 = ZonedDateTime.parse("2020-01-22T08:07:59.179-08:00");
ZoneId.of("America/Los_Angeles");
System.out.println(dateTime1.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS z")));
Run Code Online (Sandbox Code Playgroud)

此输出:2020-01-22 08:07:59.179 -08:00

请知道哪种格式输入会产生“2020-01-22 08:07:59.179 PST”

java date java-8

2
推荐指数
1
解决办法
152
查看次数

如何在java 8的forEach中使用方法引用测试Predicate

我正在尝试 forEach 内部的方法引用

private static void printConditionally8(List<Person> people, Predicate<Person> predicate) {
    people.forEach(p-> { if (predicate.test(p)){
        System.out.println("Print here");}
    });
}
Run Code Online (Sandbox Code Playgroud)

以上工作正常,但我想使用方法参考使它更短,但是它给出了编译问题。有什么办法让它发生?

private static void printConditionally8(List<Person> people, Predicate<Person> predicate) {
    people.forEach({ if (predicate::test){
        System.out.println("Print here");}
     });
}
Run Code Online (Sandbox Code Playgroud)

java lambda java-8 method-reference

2
推荐指数
1
解决办法
877
查看次数

Java Lambda | 在字符串中查找字符串数组第一次出现的位置

我想建立一个方法int getIndexOfFirstFound(String text, String[] words)

该方法接收文本和单词数组,并应返回找到的第一个单词的索引。

我知道用简单的迭代来做,就像这样:

for (String word : words) {
    if (text.indexOf(word) != -1) return text.indexOf(word);
}
return -1;
Run Code Online (Sandbox Code Playgroud)

但是对于我的培训,如果可能的话,我会看看如何使用 lambda 来做到这一点......我知道我可以检查字符串是否包含数组中的一个单词:Arrays.stream(words).parallel().anyMatch(text::contains)但我不知道如何返回索引..

很高兴知道如何用现代方式找到第一个找到的单词索引,谢谢!

PS示例:

Text= "你好我是你的短信,你好吗?" Words= [“你的”,“是”]

结果应该是“你的”(10)的索引

java lambda java-8

2
推荐指数
1
解决办法
707
查看次数

如何使用 Java 流在第一个和最后一个嵌套对象之间创建 map&lt;k,v&gt;?

假设我有以下课程:

class A {
    int id;
    List<B> b;
}

class B {
    int id;
}
Run Code Online (Sandbox Code Playgroud)

我想在 A.id 到 B.id 列表(Map<Integer, List<Integer>>,其中 key = A.id,并List<Integer>对应于每个 A 的 B.id 字段列表)之间创建一个映射。我尝试了Collectors.groupingBy和 的各种组合Collectors.mapping,但没有效果。有人可以帮我吗?

java java-8 java-stream

2
推荐指数
1
解决办法
72
查看次数

如何在 mapstruct 中使用来自不同类的另一个映射

我想将模型对象映射到 dto 模型。我已经有一个对象的映射器。如何在另一个类中的另一个映射器中重用这个映射器?

我有以下作为模型

    @Getter
    @AllArgsConstructor
    @ToString
    public class History {

      @JsonProperty("identifier")
      private final Identifier identifier;

    @JsonProperty("submitTime")
    private final ZonedDateTime submitTime;

    @JsonProperty("method")
    private final String method;

    @JsonProperty("reason")
    private final String reason;

    @JsonProperty("dataList")
    private final List<Data> dataList;
   }

     @DynamoDBTable(tableName = "history")
     @Data
     @NoArgsConstructor
     public class HistoryDynamo {
        @DynamoDBRangeKey(attributeName = "submitTime")
        @DynamoDBTypeConverted(converter = ZonedDateTimeType.Converter.class)
        private ZonedDateTime submitTime;

        @DynamoDBAttribute(attributeName = "identifier")
        @NonNull
        private Identifier identifier;

        @DynamoDBAttribute(attributeName = "method")
        private String method;

         @DynamoDBAttribute(attributeName = "reason")
         private String reason;

         @DynamoDBAttribute(attributeName = "dataList")
         private List<Data> dataList; …
Run Code Online (Sandbox Code Playgroud)

java spring java-8 mapstruct

2
推荐指数
2
解决办法
1万
查看次数