标签: java-8

收集 Map.Entry 第一个值到地图中

我有以下地图:

private static Map<String, String[]> createMap(){
    Map<String, String[]> map = new HashMap<>();
    map.put("A", new String[]{null});
    map.put("B", new String[]{"Banana"});
    map.put("C", new String[]{""});
    map.put("D", new String[]{"Duck"});
    return map;
}
Run Code Online (Sandbox Code Playgroud)

我想把这张地图转换成Map<String, String>

所需输出:

关键 :B 价值 : 香蕉

关键 :D 值 : 鸭子

我想使用Java 8 Stream APIsand 来执行此操作,并且我尝试过的解决方案之一是

final Map<String, String[]> collect = createMap().entrySet().stream()
        .filter(e -> e.getValue()[0] != null && !"".equals(e.getValue()[0]))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

collect.forEach((key, value) -> System.out.println("Key :" + key + " Value :" + Arrays.toString(value)));
Run Code Online (Sandbox Code Playgroud)

但这给了我Map<String, String[]>,输出是 …

java collections hashmap java-8 java-stream

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

Spring Cloud Stream Function :通过 REST 调用调用 Function&lt;T,R&gt; 并将其输出到 KAFKA 主题

我有简单的@Bean(Java 8 函数),它们映射到目的地topic-out-in)。

@Bean
public Function<String, String> transform() {
    return payload -> payload.toUpperCase();
}

@Bean
public Consumer<String> receive() {
    return payload -> logger.info("Data received: " + payload);
}
Run Code Online (Sandbox Code Playgroud)

.yml配置:

spring:
  cloud:
    stream:
      function:
        definition: transform;receive
      bindings:
        transform-out-0:
          destination: myTopic
        receive-in-0:
          destination: myTopic

Run Code Online (Sandbox Code Playgroud)

现在,我想transform通过调用来调用该函数REST,以便它的输出转到destination topic(即transform-out-0映射到)并由该目的地(映射到)myTopic拾取。基本上,每个 REST 调用都应该生成一个新的KAFKA实例并关闭它。consumerreceive-in-0myTopic Producer

我怎样才能做到这一点,请使用spring-cloud-stream

谢谢

安舒曼

java java-8 spring-cloud-stream spring-cloud-function

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

在过滤器 findAny 之前,地图是否应用于所有列表?

我想过滤列表中具有非空属性的元素并返回该属性:

list.stream.map(a -> StringUtils.trimToEmpty(a.getProp())).filter( p -> StringUtils.isNotEmpty(p)).findAny().orElse("");
Run Code Online (Sandbox Code Playgroud)

上面的代码是否首先映射了所有元素?出于效率原因,我想逐个元素地处理。

java short-circuiting java-8 java-stream

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

将功能接口的实现作为参数传递

函数式接口描述如下:

package models;

@FunctionalInterface
public interface EventReducer {
    void apply(Event event, GameState state);
}

Run Code Online (Sandbox Code Playgroud)

我在以下类中实现该接口:

package models.reducers;

import models.Event;
import models.EventReducer;
import models.GameState;
import models.events.MinionDeathEvent;

public class MinionDeath implements EventReducer {

    @Override
    public void apply(Event event, GameState state) {
        MinionDeathEvent deathEvent = (MinionDeathEvent)event;
        deathEvent.getPlayer().getBoard().remove(deathEvent.getMinion());
    }
}
Run Code Online (Sandbox Code Playgroud)

如何将实现作为参数传递?例如,

    private static final Map<EventType, EventReducer> ReducersMap = Map.ofEntries(
        entry(EventType.DEATH, MinionDeath::apply);
    );
Run Code Online (Sandbox Code Playgroud)

显然,MinionDeath::apply这不是一条路

java java-8 functional-interface

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

来自 python 的 Dockerfile:3.6-slim 添加 jdk8

有人可以帮助我,我从关注 docker 文件开始

FROM python:3.6-slim
RUN apt-get update
RUN apt-get install -y apt-utils build-essential gcc
Run Code Online (Sandbox Code Playgroud)

我会添加一个 openjdk 8

谢谢

java-8 docker dockerfile

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

SupplyAsync 等待所有 CompletableFutures 完成

我正在下面运行一些异步任务,需要等待它们全部完成。我不知道为什么,但它join()并没有强制等待所有任务,并且代码会继续执行而无需等待。连接流未按预期工作是否有原因?

CompletableFutures列表只是一个映射supplyAsync的流

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

List<CompletableFuture<Integer>> futures = items
                .stream()
                .map(item -> CompletableFuture.supplyAsync(() ->  {

                    System.out.println("processing");
                    // do some processing here
                    return item;

                }))
                .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

我等待期货之类的。

CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]))
                .thenApply(ignored -> futures.stream()
                        .map(CompletableFuture::join)
                        .collect(Collectors.toList()));
Run Code Online (Sandbox Code Playgroud)

我可以等待,futures.forEach(CompletableFuture::join);但我想知道为什么我的流方法不起作用。

java asynchronous java-8 completable-future

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

将 Stream&lt;String&gt; 写入文件 Java

我正在使用 java NIO 包的方法读取文件Files.lines(),该方法给出类型的输出Stream<String>。对字符串记录进行一些操作后,我想将其写入文件。我尝试使用将其收集到列表中Collectors.toList(),并且它适用于较小的数据集。当我的文件有近 100 万行(记录)时,就会出现问题,列表无法容纳那么多记录。

// Read the file using Files.lines and collect it into a List
        List<String> stringList = Files.lines(Paths.get("<inputFilePath>"))
                                    .map(line -> line.trim().replaceAll("aa","bb"))
                                    .collect(Collectors.toList());


//  Writes the list into the output file
        Files.write(Paths.get("<outputFilePath>"), stringList);
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种可以读取大文件、操作它(如.map()我的示例中的方法中所做的那样)并将其写入文件而不将其存储到列表(或集合)中的方法。

java collections stream java-8 java-stream

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

如何在java 1.8中的reduce方法中使用StringBuilder?

String s = "apples for you";
StringBuilder returnString = new StringBuilder("");
Arrays.stream(s.split(" "))
        .reduce(returnString, (acc, str) -> acc.append(str.charAt(0)));
Run Code Online (Sandbox Code Playgroud)

预期输出每个单词的第一个字母,即afy

但在acc.append,处出现错误acc被视为 a String

java string stringbuilder java-8 java-stream

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

java.time.format.DateTimeParseException:无法在索引 0 处解析文本“10-03-2021”

我试图在 Spring Boot 中使用 DateTimeFormatter 将字符串转换为 Java8 的日期格式,但收到错误 [[java.time.format.DateTimeParseException: Text '10-03-2021' Could not be parsed at index 0]] 。我使用 LocalDate 是因为我希望输出只有日期而没有时间。我的代码做错了什么。

    String date= "10-03-2021"
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE, MMM d, yyyy",Locale.forLanguageTag("sw-TZ"));
    LocalDateTime dateTime = LocalDateTime.parse(date, formatter);
    System.out.println(dateTime.format(formatter)); 
Run Code Online (Sandbox Code Playgroud)

java spring spring-mvc java-8 spring-boot

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

java 8 将字节分割成块

我必须创建一个方法,需要将文件分成多个字节。

示例 byte[] 到 List<byte[]> 中,假设每个大小为 1 MB (sizeMB=1 * 1024 * 1024)

因此 5.2 MB 文件应该由五​​个 1MB 和一个 2KB 组成。[2kb、1MB、1MB、1MB、1MB、1MB]。

byte[] mainFile=getFIle();
List<bute[]> listofSplitBytes=getFileChunks(mainFile);

public void list<bute[]> getFileChunks(byte[] mainFile) {
    int sizeMB = 1 * 1024 * 1024;
    // Split the files logic
}
Run Code Online (Sandbox Code Playgroud)

我试图避免添加if then else来处理。我正在尝试寻找是否有更干净的方法来做到这一点,例如使用流或类似的东西?

java split file java-8 java-stream

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