Java 流按键查找值(如果存在)

Joh*_*Doe 2 java java-stream

我有简单的 DataStructure

public class DataStructure {
    private String key;
    private String value;
    //get, set
}
Run Code Online (Sandbox Code Playgroud)

我需要根据键从`List'返回值,我想用流来做Java8的方式。我认为代码不言自明:

public class Main {
    public static void main(String args[]) {
      List<DataStructure> dataList = new ArrayList<>();
      dataList.add(new DataStructure("first", "123"));
      dataList.add(new DataStructure("second", "456"));

        System.out.println(findValueOldSchool(dataList, "third")); //works ok
        System.out.println(findValueStream(dataList, "third")); //throws NoSuchElementException
    }

    static String findValueOldSchool(List<DataStructure> list, String key) {
        for (DataStructure ds : list) {
            if (key.equals(ds.getKey())) {
                return ds.getValue();
            }
        }
        return null;
    }

    static String findValueStream(List<DataStructure> list, String key) {
        return list.stream()
                .filter(ds -> key.equals(ds.getKey()))
                .findFirst()
                .get().getValue();
    }
}
Run Code Online (Sandbox Code Playgroud)

我如何修改findValueStream()以在搜索不存在的键时不抛出 NoSuchValueException?不想回了,Optional<String>因为这个方法在项目很多地方已经用过了。和着,当然我心中已经试过mapifPresentanyMatch,只是找不到做正确的方式。

Nam*_*man 5

您应使用Stream.findFirstOptional.orElse这样的:

static String findValueStream(List<DataStructure> list, String key) {
    return list.stream() // initial Stream<DataStructure>
            .filter(ds -> key.equals(ds.getKey())) // filtered Stream<DataStructure>
            .map(DataStructure::getValue) // mapped Stream<String>
            .findFirst() // first Optional<String>
            .orElse(null); // or else return 'null'
}
Run Code Online (Sandbox Code Playgroud)

注意:上面使用 将Stream.map的流映射DataStructure到相应的 流value