标签: java-8

Null check vs Optional是检查

有人可以解释一下Optional我们如何避免NullPointerException吗?

Optional<String> op = someFunc()
if(op.isPresent()) {
   op.get();
}
String possibleNull = op.get();
Run Code Online (Sandbox Code Playgroud)

这个代码不是很容易出现NullPointerException吗?如果是这样,那么为什么这个代码更受欢迎

String op = someFunc()
if(op != null) {
   op.get();
}
String possibleNull = op;
Run Code Online (Sandbox Code Playgroud)

Optional除了帮助我们了解函数是否实际具有返回值之外,还有什么可能带来的好处

java functional-programming optional java-8

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

收集器(Java)中的groupingby和mapping之间有什么区别?

看看这段代码.

// group by price, uses 'mapping' to convert List<Item> to Set<String>
    Map<BigDecimal, Set<String>> result =
            items.stream().collect(
                    Collectors.groupingBy(Item::getPrice,
                            Collectors.mapping(Item::getName, Collectors.toSet())
                    )
            );
Run Code Online (Sandbox Code Playgroud)

groupingBy和Mapping是否可以互换?他们的区别是什么?

对于collect()中的第三个参数,如果我使用Collectors.toList()而不是Collectors.toSet(),我会得到相同的输出类型Map吗?我听说toList()是一个更受欢迎的选项.

java java-8 java-stream collectors

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

Java 8将int的int转换为List <Integer>

我有一个字符串:

String ints = "1, 2, 3";
Run Code Online (Sandbox Code Playgroud)

我想将其转换为整数列表:

List<Integer> intList
Run Code Online (Sandbox Code Playgroud)

我可以通过这种方式将其转换为字符串列表:

List<String> list = Stream.of("1, 2, 3").collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

但不要列出整数.

有任何想法吗?

java java-8 java-stream collectors

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

方法引用 - 无效方法引用 - 不能从静态上下文引用

我有以下一段代码

StringJoiner joiner = new StringJoiner(", ");
joiner.add("Something");
Function<StringJoiner,Integer> lengthFunc =  StringJoiner::length;
Function<CharSequence,StringJoiner> addFunc = StringJoiner::add;
Run Code Online (Sandbox Code Playgroud)

最后一行导致错误

Error:(54, 53) java: invalid method reference
  non-static method add(java.lang.CharSequence) cannot be referenced from a static context
Run Code Online (Sandbox Code Playgroud)

我知道这个方法不能以静态方式使用,我应该有类似的东西:

Function<CharSequence,StringJoiner> addFunc = joiner::add;
Run Code Online (Sandbox Code Playgroud)

代替.但是我无法理解为什么第三行,StringJoiner::length;用于java编译完全正确.someboedy可以解释一下为什么会这样吗?

java java-8

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

使用Java8 Stream从map中查找最高值

我编写了以下方法来查找映射到最高值并尝试转换为java Stream的键.你能帮忙吗?

private List<Integer> testStreamMap(Map<Integer, Long> mapGroup) 
{
    List<Integer> listMax = new ArrayList<Integer>();
    Long frequency = 0L;
    for (Integer key : mapGroup.keySet()) {
        Long occurrence = mapGroup.get(key);
        if (occurrence > frequency) {
            listMax.clear();
            listMax.add(key);
            frequency = occurrence;
        } else if (occurrence == frequency) {
            listMax.add(key);
        }
    }
    return listMax;
}
Run Code Online (Sandbox Code Playgroud)

java java-8 java-stream

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

将字符串"yyyy-MM-dd"转换为LocalDateTime

有什么办法转换的日期StringLocalDateTime了格式"yyyy-MM-dd"

如果我试试这个:

DateTimeFormatter DATEFORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDateTime ldt = LocalDateTime.parse(string, DATEFORMATTER);
Run Code Online (Sandbox Code Playgroud)

我有这个例外:

java.time.format.DateTimeParseException: Text '2017-03-13' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2017-03-13 of type java.time.format.Parsed
    at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
    at java.time.LocalDateTime.parse(LocalDateTime.java:492)
    at hu.npsh.workforce.utils.Util.stringToLocalDateTime(Util.java:284)
    at hu.npsh.workforce.utils.util.StringLocalDateTimeConversionTest.stringToLocalDateTimeTest(StringLocalDateTimeConversionTest.java:35)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at …
Run Code Online (Sandbox Code Playgroud)

java date date-parsing java-8

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

如何使用Hibernate映射java.time.Year和其他java.time类型

hibernate-java8JAR了几个类似的类提供适配器Instant,LocalDate等等,但是从一些类java.time,例如Year,Month,YearMonth失踪.这些类被存储为未知的Serializable,这是不必要的浪费.

当然我可以使用int year而不是Year year,但我不认为,这是一个好主意.

看起来YearJavaDescriptor应该很容易写,但是,我想知道为什么它会丢失.特别是在情况下YearMonth,我非常喜欢现有的适配器,不是吗?或者我做了一些愚蠢的事情?

我不确定谷歌搜索没有返回任何东西.

java hibernate java-8 java-time

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

BigDecimal #min方法是否有资格作为BinaryOperator?

Stream.reduce方法以a BinaryOperator为参数.a的函数签名BinaryOperator(T,T) -> T.该BigDecimal::min方法在其方法签名中只有1个参数(即.(T) -> T).

当我传递BigDecimal::minStream.reduce方法时,为什么编译器不会抱怨?

示例代码:

List<BigDecimal> bigDecimalList = new ArrayList<>();
        bigDecimalList.add(BigDecimal.valueOf(1));
        bigDecimalList.add(BigDecimal.valueOf(2));
        bigDecimalList.add(BigDecimal.valueOf(3));
BigDecimal minResult = bigDecimalList.stream().reduce(BigDecimal::min).orElse(BigDecimal.ZERO);
Run Code Online (Sandbox Code Playgroud)

谢谢.

java java-8 java-stream

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

在Stream API中使用AutoClosable接口

今天我试着重构这个代码,它从目录中的文件中读取id,

Set<Long> ids = new HashSet<>();
for (String fileName : fileSystem.list("my-directory")) {
    InputStream stream = fileSystem.openInputStream(fileName);
    BufferedReader br = new BufferedReader(new InputStreamReader(stream));
    String line;
    while ((line = br.readLine()) != null) {
        ids.add(Long.valueOf(line.trim()));
    }
    br.close();
}
Run Code Online (Sandbox Code Playgroud)

使用流api

Set<Long> ids = fileSystem.list("my-directory").stream()
    .map(fileName -> fileSystem::openInputStream)
    .map(is -> new BufferedReader(new InputStreamReader(is)))
    .flatMap(BufferedReader::lines)
    .map(String::trim)
    .map(Long::valueOf)
    .collect(Collectors.toSet());
Run Code Online (Sandbox Code Playgroud)

然后我发现IO流不会被关闭,我没有看到一种简单的方法来关闭它们,因为它们是在管道内创建的.

有任何想法吗?

upd:示例中的FileSystem是HDFS,Files#lines不能使用类似的方法.

java java-io java-8 java-stream autocloseable

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

使用Java 8 Stream API从对象列表中收集列表

我有这样的课

public class Example {
    private List<Integer> ids;

    public getIds() {
        return this.ids; 
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我有这样的类的对象列表

List<Example> examples;
Run Code Online (Sandbox Code Playgroud)

我怎样才能将所有示例的id列表映射到一个列表中?我试过这样的:

List<Integer> concat = examples.stream().map(Example::getIds).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

但得到一个错误 Collectors.toList()

使用Java 8 stream api获得此功能的正确方法是什么?

java java-8

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