相关疑难解决方法(0)

Java lambdas 堆转储 - lambda 实例没有被垃圾收集

我在用 java 生成应用程序时遇到了一些垃圾收集问题,我使用 Stream.map 修剪列表中的所有元素。匿名 lambda 类的实例存在于堆转储中,即使封闭类的实例为 0,如可视化 VM 的快照所示。

在此处输入图片说明

LambdaTesting 类:

class LambdaTesting {

    protected List<String> values;

    protected LambdaTesting(List<String> values) {
        this.values = values;
    }
    public List<String> modify() {      
        return this.values.stream().map(x -> x.trim()).collect(Collectors.toList());
    }
    public List<String> modifyLocal() {
        List<String> localValue = new ArrayList<>();
        localValue.add("Local FOO ");
        localValue.add("Local BAR ");
        return localValue.stream().map(x -> x.trim()).collect(Collectors.toList());     
   }
}
Run Code Online (Sandbox Code Playgroud)

创建 LambdaTesting 实例并调用这些方法的方法:

public List<String> testMethods() {
    List<String> test = new ArrayList<>();      
    test.add("Global FOO  ");
    test.add("   GLOBAL BAR");  
    LambdaTesting lambdaTesting = new LambdaTesting(test);
    lambdaTesting.modifyLocal(); …
Run Code Online (Sandbox Code Playgroud)

java lambda garbage-collection java-8 java-stream

5
推荐指数
1
解决办法
363
查看次数

Java 8 -reduce(0, Integer::sum) 和reduce(0, (a, b) -&gt; a+b) 之间的区别

我是新手Java 8,确实找到了一些方法additionmultiply并且subtraction。我将发布仅用于添加的问题。

我编写了下面的代码并在 Sum1 和 Sum2 中收集输出。这两种方法reduce(0, Integer::sum)给出.reduce(0, (a, b) -> a+b);了相同的结果。如果使用大整数值,最好的使用性能的方法是什么?为什么?

List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 3, 2, 4);

Integer sum1 = numbers.stream().reduce(0, (a, b) -> a+b);
System.out.println("SUM ="+sum1);

Integer product = numbers.stream().reduce(0, (a, b) -> a*b);
System.out.println("PRODUCT = "+product);

int sum2 = numbers.stream().reduce(0, Integer::sum);
System.out.println("SUM 2= "+sum2);

Optional<Integer> sum3 = numbers.stream().reduce((a, b) -> (a + b));
System.out.println("SUM3="+sum3);

// Updated as per  @Hadi J comment …
Run Code Online (Sandbox Code Playgroud)

java collections reduce java-8 java-stream

4
推荐指数
1
解决办法
3600
查看次数

Java 多线程中的 Thread、Runnable 和 CompletableFuture

我正在尝试在我的 Spring Boot 应用程序中实现多线程。我只是 Java 多线程的初学者,在进行了一些搜索并阅读了各个页面上的文章后,我需要澄清以下几点。所以;

  1. 据我所知,我可以使用Thread,RunnableCompletableFuture来在 Java 应用程序中实现多线程。CompletableFuture似乎是一种更新、更清洁的方式,但Thread可能有更多优点。那么,我应该根据场景坚持使用CompletableFuture还是全部使用?

  2. 基本上我想使用以下方法向同一个服务方法发送 2 个并发请求CompletableFuture

    CompletableFuture<Integer> future1 = fetchAsync(1);
    CompletableFuture<Integer> future2 = fetchAsync(2);
    
    Integer result1 = future1.get();
    Integer result2 = future2.get();
    
    Run Code Online (Sandbox Code Playgroud)

如何同时发送这些请求,然后根据以下条件返回结果:

  • 如果第一个结果不为空,则返回结果并停止进程
  • 如果第一个结果为空,则返回第二个结果并停止进程

我怎样才能做到这一点?我应该用CompletableFuture.anyOf()它吗?

java spring multithreading process completable-future

4
推荐指数
1
解决办法
1299
查看次数

为什么我不能在 Optional.filter 的参数中用 Function.identity() 替换 (t -&gt; t) ?

我有一些看起来像这样的代码(这里简化了):

public Optional<String> parseInput(String input){
    Pattern pattern = Pattern.compile("([A-Za-z]+)([0-9]{2}|[0-9]{4})");
    Matcher matcher = pattern.matcher(input);
    return Optional.of(matcher.find())
                   .filter(t -> t) // .filter(Function.identity())
                   .map(ignore -> matcher.group(1));
}
Run Code Online (Sandbox Code Playgroud)

但它失败并出现错误:

Error: incompatible types: no instance(s) of type variable(s) T exist so that java.util.function.Function<T,T> conforms to java.util.function.Predicate<? super java.lang.Boolean>

这里发生了什么,为什么要这样设计?

java java-8

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

什么时候在Java中使用Identity函数?

通过一些代码,并遇到Function.identity(),我发现它类似于s-> s。我不明白为什么以及何时应该使用Function.identity()。

我试图通过一个例子来理解,但是并没有阐明我的问题:

public static void main(String[] args){
        Arrays.asList("a", "b", "c")
          .stream()
          .map(Function.identity())
          //.map(str -> str)   //it is the same as identity()       
          .forEach(System.out::println);
        return;
    }
Run Code Online (Sandbox Code Playgroud)

当打印带有和不带有映射的列表元素时,我得到相同的结果:

a
b
c
Run Code Online (Sandbox Code Playgroud)

那么,包含s-> s的目的是传递字符串并检索字符串吗?Function.identity()的目的是什么?

请给我提供一个更好的示例,也许这个示例对证明使用identity()的重要性没有意义。

谢谢

java lambda functional-programming java-8

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

为什么Java不能检查这段代码?

我有一些流处理代码,它接受单词流并对它们执行一些操作,然后将它们缩减为Map包含单词作为键和单词作为Long值出现的次数.为了简洁代码,我使用了jOOL库Seq类,它包含许多有用的快捷方法.

如果我像这样编写它,代码编译就好了:

item.setWordIndex (
        getWords (item)                      // returns a Seq<String>
              .map (this::removePunctuation) // String -> String
              .map (stemmer::stem)           // String -> String
              .groupBy(str -> str, Collectors.counting ()));
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试str -> str用更多自我文档替换lambda Function::identity,我会收到以下错误:

setWordIndex(Map<String,Long>)类型中的方法MyClass不适用于参数(Map<Object,Long>)
类型Function没有定义identity(String)适用于此处

为什么我的Function::identity行为有任何不同str -> str,我(或许天真地)假设它是直接等价的,为什么编译器在使用它时不能处理它?

(是的,我知道我可以通过将先前的map应用程序移动到groupBy操作中来删除身份功能,但我发现代码更清晰,因为它更直接地遵循应用程序逻辑)

java generics typechecking

0
推荐指数
1
解决办法
76
查看次数

在 Java 中,为什么 Function.identity() 是静态方法而不是其他方法?

Java 8 添加了函数式编程结构,包括Function类及其关联identity()方法。

这是此方法的当前结构:

// Current implementation of this function in the [JDK source][1]
static <T> Function<T, T> identity() {
    return t -> t;
}

// Can be used like this
List<T> sameList = list.stream().map(Function.identity()).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

但是,还有第二种构造它的方法:

// Alternative implementation of the method
static <T> T identity(T in) {
    return in;
}

// Can be used like this
List<T> sameList = list.stream().map(Function::identity).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

甚至还有第三种方式来构建它:

// Third implementation
static final Function<T, T> IDENTITY_FUNCTION = t -> t;

// Can …
Run Code Online (Sandbox Code Playgroud)

java functional-programming java-8 functional-interface

0
推荐指数
1
解决办法
423
查看次数