标签: java-8

如何在Java中使用带原始返回或参数类型的函数?

在Java 8中,有一个类似于函数指针(java.util.function.Function)的功能.它通常像这样使用:Function<LookupKey,LookupResult>但是,如果方法返回基本类型则存在问题.Function<ArgType,Void.TYPE>不起作用,它无法编译一个非常混乱的错误消息("找不到符号Void.TYPE").我宁愿避免更改我的方法返回一个Object只是为了传递null作为结果.

generics functional-programming java-8

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

Java 8-用于循环的immutablemap

对Java来说,我是新手,最初使用了hashmap并对此进行了forEach操作,效果很好:

Map<String, Integer> testmap = new HashMap<>();
IntStream.range(0, 100).forEach(n -> {
                testmap.put("teststring-" + Integer.toString(n), 1);
            });
String x = testmap.entrySet().stream().filter(..);
Run Code Online (Sandbox Code Playgroud)

但是,现在我有一个ImmutableHashMap,我想在上述步骤中做同样的事情,我该怎么做?我试着做

ImmutableMap.Builder<String, Integer> testmap = ImmutableMap.builder(); 
IntStream.range(0, 100).forEach(n -> {
            testmap.put("teststring-" + Integer.toString(n), 1);
        });
testmap.build();
String x = testmap.entrySet().stream().filter(...); // throws an error while compile

cannot find symbol
    [javac]         String testmap = testmap.entrySet().stream()
    [javac]                                ^
    [javac]   symbol:   method entrySet()
    [javac]   location: variable streams of type Builder<String,Integer>
Run Code Online (Sandbox Code Playgroud)

谁能指出我在这里做错了什么?非常感谢您的帮助!

java guava java-8

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

使用Java 8动态创建具有组合键的映射

我想创建一个类似下面的地图 - >

Map<Pair<MyClass.a, MyClass.b>, MyClass>>.
Run Code Online (Sandbox Code Playgroud)

我有一个对象列表 - >

List<MyClass>
Run Code Online (Sandbox Code Playgroud)

这里的Pair是一个类,已经在我的项目中,所以我想使用它.

我需要帮助从Java 8流创建它.

我试过::

ls.stream().collect(Collectors.toMap(new Pair(MyClass.a, MyClass.b), MyClass));
Run Code Online (Sandbox Code Playgroud)

但是我收到了一个错误.我是Java 8的新手并且正在努力学习它.

添加示例:

class Person {
   String name ;
   int age ;
   // Some other variables
}
Run Code Online (Sandbox Code Playgroud)

我有一份清单List<Person>.

在我的要求中,我需要一个键= {name,age},使用对类.

class Pair<T,U> {     
    Pair(T t, U u) {
        this.t = t
        this.u = u
    }

    // Overridden hashCode && equals methods
}
Run Code Online (Sandbox Code Playgroud)

现在我想创建一个类似的地图 Map<Pair<String, Int>, Person>

我收到一个编译器错误,说"不是一个功能接口".

我相信必须通过java 8流和收集方式.

java-8

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

LongAccumulator无法获得正确的结果

代码优先:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.LongAccumulator;
import java.util.function.LongBinaryOperator;
import java.util.stream.IntStream;

/**
 * Created by tom on 17-4-13.
 */
public class ForSOF {
    public static void main(String[] args){
        LongBinaryOperator op = (v, y) -> (v*2 + y);
        LongAccumulator accumulator = new LongAccumulator(op, 1L);

        ExecutorService executor = Executors.newFixedThreadPool(2);

        IntStream.range(0, 10)
                .forEach(i -> executor.submit(() -> accumulator.accumulate(i)));

        stop(executor);

        // 2539 expected, however result does not always be! I had got 2037 before.
        System.out.println(accumulator.getThenReset());
    }

    /**
     * codes for stop the executor, …
Run Code Online (Sandbox Code Playgroud)

java concurrency multithreading java-8

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

我可以给lambda一个名字吗?

我有很好的功能代码粗略的下一个形状(ComponentRegistry.java):

public void doExport() {
    config.exports().forEach((key, type) -> {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

它的问题是,当涉及到log4j语句时,它会产生下一个输出:

ComponentRegistry lambda$doExport$1
Run Code Online (Sandbox Code Playgroud)

其中实际的方法名称位于"lambda"关键字之后,然后有两个关于匿名类($)的提示.它不如直接方法调用日志记录好.

我想知道是否有人在log4j输出或stacktraces中正确标记lambdas,因为它会很棒.

java lambda java-8

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

子子流中列表大小的总和

我有以下结构:

class A {
    List<B> bs;   
}

class B {
    List<C> cs;
}

class C {
    List something.
}
Run Code Online (Sandbox Code Playgroud)

ListA班,我要进去的所有元素的SUMM something名单.我试着做以下事情:

    totalCount = as
            .stream()
            .map(a -> a.getBs()
                    .stream()
                    .mapToInt(b -> b.getSomething().size())
                    .sum());
Run Code Online (Sandbox Code Playgroud)

但那不编译.我的错误在哪里?

编译错误是: Error:(61, 21) java: incompatible types: no instance(s) of type variable(s) R exist so that java.util.stream.Stream<R> conforms to java.lang.Integer

java java-8 java-stream

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

在Java 8中将匿名内部方法转换为Lambda

如何使用Java 8将以下代码(特别是public void run()方法)转换为lambda?

public class SampleApp {

    public static void main(String[] args) {
        Thread t1 = new Thread(new Runnable() {

            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    System.out.println("Hello " + i);
                    try {
                        Thread.sleep(100);
                    }
                    catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        t1.start();
    }
}
Run Code Online (Sandbox Code Playgroud)

尝试:

Thread t1 = new Thread(new Runnable() -> {

    for (int i = 0; i < 10; i++) {
        System.out.println("Hello " + i);
        try …
Run Code Online (Sandbox Code Playgroud)

java lambda java-8

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

返回Java 8 forEach

 Boolean isSuccess = true;
    if(aMap.size() != bMap.size())
    {
        return false;
    }

    aMap.entrySet().forEach(entry -> {
        AKey aKey = entry.getKey();
        BValue bValue = bMap.get(aKey);

        if(bValue == null)
            return;

        AValue aValue = entry.getValue();
        if(!aValue.getClosed().equals(bValue.getClosed()))
            return;

        if(!aValue.getClosedToArrival().equals(bValue.getClosedToArrival()))
            return;

        if(!aValue.getClosedToDeparture().equals(bValue.getClosedToDeparture()))
            return;

        if(!aValue.getLengthOfStayArrival().equals(bValue.getLengthOfStayArrival()))
            return;
    });

    return isSuccess;
Run Code Online (Sandbox Code Playgroud)

验证失败时如何返回false?我试图添加return false,如下所示:

if(!aValue.getLengthOfStayArrival().equals(bValue.getLengthOfStayArrival()))
        return false; 
Run Code Online (Sandbox Code Playgroud)

但这是意料之外的表达,谁能帮我看看?

foreach java-8

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

删除null元素后java8 make immutable List

我知道Arrays.asList创造不变List.我的要求是创建不可变的List<Student>,不包含任何null元素.所以我new ArrayList()先创建然后null使用java 8 删除元素filters,如下所示:

List<Student> list = new ArrayList<>();
list.add(makeStudent("ram", 'M'));
list.add(makeStudent("sathya", 'F'));
list.add(makeStudent(null, 'M'));
list.add(makeStudent("sri", 'M'));

list = list.stream().filter(s -> s != null).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

以下是makeStudent方法,null如果名称不可用则返回:

private Student makeStudent(String name, char gender) {
    return null != name ? new Student(name, gender) : null;
}
Run Code Online (Sandbox Code Playgroud)

我以为Collectors.toList()会创造不变的.但是我错了.在list这里仍然是可变的.有没有更好的方法来使用单行进行list清理(​​删除null)和不可变java 8

arraylist immutability java-8

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

CompletableFuture.thenAccept中使用的垃圾收集对象的可用性

我试图从使用的方法执行异步调用CompletableFuture.完成该任务后,我试图打印对象DummyObject的值,这些对象是调用异步调用的方法的本地对象.

我想知道它是如何工作的?thread(myThread)在3秒后死亡,DummyObject超出范围,thenAccept中的Async回调仍然打印正确的值.线程是否在DummyObject上获得锁定?或者其他事情正在发生?

请注意,我只是想模拟一个场景.所以我正在使用Thread.stop().

编辑 - 问题是关于thenAccept Consumer如何处理范围?请保持与此相关的答案.

以下计划的输出:

Starting Async stuff
Thread Alive?  false
Reached Main end and waiting for 8 more seconds
James T. Kirk
United Federation of Planets
Run Code Online (Sandbox Code Playgroud)

AsyncTest.java

public class AsyncTest {

    public static void main(String args[]) {

        Thread myThread = new Thread() {
            @Override
            public void run() {
                DummyObject dummyObj = new DummyObject();
                dummyObj.setObjectName("James T. Kirk");
                dummyObj.setObjectNationality("United Federation of Planets");
                System.out.println("Starting Async stuff");
                new AsyncTaskExecuter().executeAsync().thenAccept(taskStatus -> {
                    if(taskStatus.booleanValue()) {
                        System.out.println(dummyObj.getObjectName()); …
Run Code Online (Sandbox Code Playgroud)

java concurrency asynchronous java-8 completable-future

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