标签: java-8

如何将(Optional.isPresent())替换为函数样式的表达式

我有以下代码块:

Optional<Integer> result = //some method that returns an Optional<Integer>;

    if(result.isPresent()) {
        return result.get();
    } else {
        return 0;
    }
Run Code Online (Sandbox Code Playgroud)

我的IntelliJ建议我用功能表达式替换它.我看到里面有一个方法ifPresentOrElse(),Optional但我无法弄清楚如何在这种特殊情况下使用它.

有什么建议?谢谢!

java java-8 java-stream

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

java中lambda表达式的副作用

请考虑以下代码段.

List<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
List<String> copyList = new ArrayList<String>(); 
Consumer<String> consumer = s->copyList.add(s);
list.stream().forEach(consumer);
Run Code Online (Sandbox Code Playgroud)

由于我们使用lambda表达式,根据函数式编程(纯函数),它应该只计算输入并提供相应的输出.

但是在这个示例中,它试图将元素添加到列表中,既不是输入也不是在lambda范围内声明.

这是一个很好的做法,我的意思是,导致任何副作用?

java functional-programming java-8

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

Streams - 过滤所有不抛出异常

假设我有一个Reports流,我有一个方法可以检查用户是否有权读取每个报告.如果用户没有权限,此方法将抛出异常

checkReadAuthorization(Report report) throw AccessViolationException;
Run Code Online (Sandbox Code Playgroud)

有没有办法过滤掉此方法引发异常的所有报告?就像是:

reports.stream()
.filterThrowingException(this::checkReadAuthorization);
Run Code Online (Sandbox Code Playgroud)

现在我有一个函数,如果抛出异常则返回true或false但是我想知道是否有更好的方法来实现这个

private boolean checkAuthorization(Report report) {
    try {
        checkReadAuthorization(report);
        return true;
    } catch(AccessViolationException ex) {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我在这样的过滤器中使用它

return dossiers.stream()
    .filter(this::checkAuthorization)
    .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

java exception list java-8 java-stream

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

Java Streams列表将映射的索引映射为键

假设我有一个字符串列表

["bird", "bird", "dog", "dog", "bird","bog"]
Run Code Online (Sandbox Code Playgroud)

我希望它们以形式收集为地图

{"bird": [0, 1, 4], "dog": [2, 3, 5]}
Run Code Online (Sandbox Code Playgroud)

作为列表值是单词在输入列表中的索引.

有没有办法用Java Streams做到这一点?

java grouping java-8 java-stream

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

使用If条件迭代ArrayList并使用流api返回boolean标志

我试图让自己更熟悉Java 8 Stream api.目前我想翻译像流一样的东西,但似乎我仍然不够舒服,因为我不知道如何做到这一点.

boolean isTrue = false;

for (Integer integer : intList) {
    if (integer > 10) {
        isTrue = true;
        break;
    }
}
Run Code Online (Sandbox Code Playgroud)

java java-8

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

具有Runnable-delegation的CompletableFuture - 在委派类时忽略异常

我在使用CompletableFuture将代码转换为非阻塞代码时遇到了问题.为了最小化问题的范围,我创建了一个示例代码,当我使用CompletableFuture时,该代码的行为有所不同.问题是CompletableFuture从Runnable-delegation吞下异常.

我在Runnable和ExecutorService之上使用委托来提供我原始应用程序中所需的一些包装代码.

示例代码:

  • MyRunnable:我的示例runnable,它总是抛出异常.

    public class MyRunnable implements Runnable {
    
        @Override
        public void run() {
            System.out.println("This is My Thread throwing exception : " + Thread.currentThread().getName());
            throw new RuntimeException("Runtime exception from MyThread");
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • DelegatingRunnable - 这是委托runnable,它委托并包装传递给它的Runnable的逻辑,以及用于异常处理的占位符.

    public class DelegatingRunnable implements Runnable {
    
        private Runnable delegate; 
    
        public DelegatingRunnable(Runnable delegate) {
            this.delegate = delegate;
        }
    
        @Override
        public void run() {
            System.out.println("Delegating Thread start : " + Thread.currentThread().getName());
            try {
                // Some code before thread execution
                delegate.run();
                // Some …
    Run Code Online (Sandbox Code Playgroud)

java java-8 completable-future

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

如何将Set <String>转换为Long []在java8中使用Lambda表达式

任何人都可以告诉如何转换Set of String valuesLong Array values.

String singleId = "8432";
String[] ids = new String[]{"4562", "8432"};
Set<String> setIds = new HashSet<String>();
if (setIds != null && ids.length > 0){
    for (String id : ids){
        setIds.add(id);
    }
    setIds.add(singleId);
} else {
    setIds.add(singleId);
}
Long[] longIds = setIds.stream().toArray(Long[]::new);
System.out.println(longIds);
Run Code Online (Sandbox Code Playgroud)

低于错误

Exception in thread "main" java.lang.ArrayStoreException: java.lang.String
at java.util.stream.Nodes$FixedNodeBuilder.accept(Nodes.java:1222)
at java.util.HashMap$KeySpliterator.forEachRemaining(HashMap.java:1540)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:545)
at java.util.stream.AbstractPipeline.evaluateToArrayNode(AbstractPipeline.java:260)
at java.util.stream.ReferencePipeline.toArray(ReferencePipeline.java:438)
at com.java.collections.set.FilterDuplicatesBySet.main(FilterDuplicatesBySet.java:40)
Run Code Online (Sandbox Code Playgroud)

java collections lambda java-8 arraystoreexception

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

转换Object并使用java中的递归字段换行到另一个

出于某些原因,我需要一个新对象来包装我从其他API获得的数据.

我遇到的问题是不知道从原始对象处理递归字段.

以下是示例代码:

//original object
public class Resource{
    private String name;
    private String content;
    private Integer type;
    private List<Resource> children = new LinkedList();
    public void addChildrenResource(Resource children) {
        this.children.add(children);
    }
    //getters&setters...
}
Run Code Online (Sandbox Code Playgroud)
//the object try to convert
public class Menu{
    private String name;
    private String url;
    private Integer type;
    private List<Menu> subMenu = new LinkedList();
    public void addChildrenResource(Menu subMenu) {
        this.children.add(subMenu);
    }
    //getters&setters...
}
Run Code Online (Sandbox Code Playgroud)

我做的实现,我不知道与递归字段...
这是我的代码..

List<Resource> resources = rpcService.getResources();

//Here I can't handle the subMenu or children part..
List<Menu> …
Run Code Online (Sandbox Code Playgroud)

java recursion java-8 java-stream

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

如何为Java 8并行流指定ForkJoinPool?

据我所知,并行流使用默认值ForkJoinPool.commonPool,默认情况下,线程数比处理器少一个.我想使用自己的自定义线程池.

像这样:

@Test
public void stream() throws Exception {
    //System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "20");
    ForkJoinPool pool = new ForkJoinPool(10);
    List<Integer> testList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
    long start = System.currentTimeMillis();
    List<Integer> result = pool.submit(() -> testList.parallelStream().map(item -> {
        try {
            // read from database
            Thread.sleep(1000);
            System.out.println("task" + item + ":" + Thread.currentThread());
        } catch (Exception e) {
        }
        return item * 10;
    })).get().collect(Collectors.toList());
    System.out.println(result);
    System.out.println(System.currentTimeMillis() …
Run Code Online (Sandbox Code Playgroud)

java-8 java-stream

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

lambda从map中检索整数

我试图在使用Lambda表达式进行计算后得到数字,但得到错误.

我正在使用的lambda表达式:

int num = Optional.ofNullable(list.stream().filter(x->x.getType().getTypeId()==Type.getTypeId()).limit(1).map(x->x.getNum())).get();
Run Code Online (Sandbox Code Playgroud)

过滤后,我想获得第一个检索到的值.但我得到的错误是

cannot convert from Stream<Integer> to int
Run Code Online (Sandbox Code Playgroud)

所以,目前我使用的方式是

Optional<> li = list.stream().filter(x->x.getType().getTypeId()==Type.getTypeId()).findFirst();
if (li.isPresent()) {
    num = li.map(x-> x.getNum()).get();
}
Run Code Online (Sandbox Code Playgroud)

但是,我正在寻找上述是否可以在一行而不是额外的if声明

早些时候,我试图get()findFirst(),但它给人nullpointerException.如何安全地检索该值.

java lambda dictionary java-8

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