标签: java-8

Lambda表达式和通用方法

假设我有一个通用接口:

interface MyComparable<T extends Comparable<T>>  {
    public int compare(T obj1, T obj2);
}
Run Code Online (Sandbox Code Playgroud)

一个方法sort:

public static <T extends Comparable<T>> 
       void sort(List<T> list, MyComparable<T> comp) {
    // sort the list
}
Run Code Online (Sandbox Code Playgroud)

我可以调用此方法并将lambda表达式作为参数传递:

List<String> list = Arrays.asList("a", "b", "c");
sort(list, (a, b) -> a.compareTo(b));
Run Code Online (Sandbox Code Playgroud)

那会很好.

但现在如果我使接口非泛型,并且方法通用:

interface MyComparable {
    public <T extends Comparable<T>> int compare(T obj1, T obj2);
}

public static <T extends Comparable<T>> 
       void sort(List<T> list, MyComparable comp) {
}
Run Code Online (Sandbox Code Playgroud)

然后调用它:

List<String> list = Arrays.asList("a", "b", "c");
sort(list, (a, …
Run Code Online (Sandbox Code Playgroud)

java generics lambda java-8

103
推荐指数
3
解决办法
6万
查看次数

是否有收集到订单保留集的收集器?

Collectors.toSet()不保留秩序.我可以使用Lists代替,但我想指出结果集合不允许元素重复,这正是Set接口的用途.

java java-8 collectors

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

为什么java.util.Optional不是Serializable,如何使用这些字段序列化对象

Enum类是Serializable,因此使用枚举序列化对象没有问题.另一种情况是class具有java.util.Optional类的字段.在这种情况下,抛出以下异常:java.io.NotSerializableException:java.util.Optional

如何处理这些类,如何序列化它们?是否可以将此类对象发送到远程EJB或通过RMI?

这是一个例子:

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Optional;

import org.junit.Test;

public class SerializationTest {

    static class My implements Serializable {

        private static final long serialVersionUID = 1L;
        Optional<Integer> value = Optional.empty();

        public void setValue(Integer i) {
            this.i = Optional.of(i);
        }

        public Optional<Integer> getValue() {
            return value;
        }
    }

    //java.io.NotSerializableException is thrown

    @Test
    public void serialize() {
        My my = new My();
        byte[] bytes = toBytes(my);
    }

    public static <T extends Serializable> byte[] toBytes(T reportInfo) { …
Run Code Online (Sandbox Code Playgroud)

java serialization optional java-8

101
推荐指数
4
解决办法
3万
查看次数

Comparator.reversed()不使用lambda进行编译

我有一个包含一些User对象的列表,我正在尝试对列表进行排序,但只能使用方法引用,使用lambda表达式,编译器会给出错误:

List<User> userList = Arrays.asList(u1, u2, u3);
userList.sort(Comparator.comparing(u -> u.getName())); // works
userList.sort(Comparator.comparing(User::getName).reversed()); // works
userList.sort(Comparator.comparing(u -> u.getName()).reversed()); // Compiler error
Run Code Online (Sandbox Code Playgroud)

错误:

com\java8\collectionapi\CollectionTest.java:35: error: cannot find symbol
            userList.sort(Comparator.comparing(u -> u.getName()).reversed());
                                                     ^
symbol:   method getName()
location: variable u of type Object
1 error
Run Code Online (Sandbox Code Playgroud)

java lambda java-8 method-reference

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

在一行中获取流/列表的最后一个元素

如何在以下代码中获取流或列表的最后一个元素?

哪里data.careasList<CArea>:

CArea first = data.careas.stream()
                  .filter(c -> c.bbox.orientationHorizontal).findFirst().get();

CArea last = data.careas.stream()
                 .filter(c -> c.bbox.orientationHorizontal)
                 .collect(Collectors.toList()).; //how to?
Run Code Online (Sandbox Code Playgroud)

正如你所看到的那样,获得第一个元素filter并不难.

然而,获得单行中的最后一个元素是一个真正的痛苦:

  • 好像我不能直接从a获得它Stream.(它只对有限流有意义)
  • 这似乎也不能得到像first()last()List接口,这实在是一种痛苦.

我没有看到任何关于不在接口中提供first()last()方法的论据List,因为其中的元素是有序的,而且大小是已知的.

但根据原始答案:如何获得有限的最后一个元素Stream

就个人而言,这是我能得到的最接近的:

int lastIndex = data.careas.stream()
        .filter(c -> c.bbox.orientationHorizontal)
        .mapToInt(c -> data.careas.indexOf(c)).max().getAsInt();
CArea last = data.careas.get(lastIndex);
Run Code Online (Sandbox Code Playgroud)

然而,它确实涉及使用indexOf每个元素,这很可能不是您通常想要的,因为它可能会影响性能.

java list java-8 java-stream

100
推荐指数
5
解决办法
7万
查看次数

使用新的日期时间API格式化日期

我正在使用新的日期时间API,但在运行时:

public class Test {         
    public static void main(String[] args){
        String dateFormatted = LocalDate.now()
                                        .format(DateTimeFormatter
                                              .ofPattern("yyyy-MM-dd HH:mm:ss"));
        System.out.println(dateFormatted);
    }
}
Run Code Online (Sandbox Code Playgroud)

它抛出:

Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: HourOfDay
    at java.time.LocalDate.get0(LocalDate.java:680)
    at java.time.LocalDate.getLong(LocalDate.java:659)
    at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298)
    at java.time.format.DateTimeFormatterBuilder$NumberPrinterParser.format(DateTimeFormatterBuilder.java:2543)
    at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2182)
    at java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1745)
    at java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1719)
    at java.time.LocalDate.format(LocalDate.java:1685)
    at Test.main(Test.java:23)
Run Code Online (Sandbox Code Playgroud)

查看LocalDate类的源代码时,我看到:

  private int get0(TemporalField field) {
        switch ((ChronoField) field) {
            case DAY_OF_WEEK: return getDayOfWeek().getValue();
            case ALIGNED_DAY_OF_WEEK_IN_MONTH: return ((day - 1) % 7) + 1;
            case ALIGNED_DAY_OF_WEEK_IN_YEAR: return ((getDayOfYear() - 1) % 7) + …
Run Code Online (Sandbox Code Playgroud)

java datetime java-8 java-time

100
推荐指数
3
解决办法
6万
查看次数

复制流以避免"流已经被操作或关闭"

我想复制Java 8流,以便我可以处理它两次.我可以collect作为一个列表并从中获得新的流;

// doSomething() returns a stream
List<A> thing = doSomething().collect(toList());
thing.stream()... // do stuff
thing.stream()... // do other stuff
Run Code Online (Sandbox Code Playgroud)

但我认为应该有一种更有效/更优雅的方式.

有没有办法复制流而不将其转换为集合?

我实际上正在使用Eithers 流,所以想要在移动到正确的投影之前以一种方式处理左投影并以另一种方式处理.有点像这样(到目前为止,我被迫使用这个toList技巧).

List<Either<Pair<A, Throwable>, A>> results = doSomething().collect(toList());

Stream<Pair<A, Throwable>> failures = results.stream().flatMap(either -> either.left());
failures.forEach(failure -> ... );

Stream<A> successes = results.stream().flatMap(either -> either.right());
successes.forEach(success -> ... );
Run Code Online (Sandbox Code Playgroud)

java lambda java-8 java-stream

100
推荐指数
6
解决办法
5万
查看次数

在Java8中使用Timezone格式化LocalDateTime

我有这个简单的代码:

DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z");
LocalDateTime.now().format(FORMATTER)
Run Code Online (Sandbox Code Playgroud)

然后我会得到以下异常:

java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: OffsetSeconds
at java.time.LocalDate.get0(LocalDate.java:680)
at java.time.LocalDate.getLong(LocalDate.java:659)
at java.time.LocalDateTime.getLong(LocalDateTime.java:720)
at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298)
at java.time.format.DateTimeFormatterBuilder$OffsetIdPrinterParser.format(DateTimeFormatterBuilder.java:3315)
at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2182)
at java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1745)
at java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1719)
at java.time.LocalDateTime.format(LocalDateTime.java:1746)
Run Code Online (Sandbox Code Playgroud)

如何解决这个问题?

java java-8 java-time

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

为什么ZoneOffset.UTC!= ZoneId.of("UTC")?

为什么

ZonedDateTime now = ZonedDateTime.now();
System.out.println(now.withZoneSameInstant(ZoneOffset.UTC)
        .equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
Run Code Online (Sandbox Code Playgroud)

打印出来false

我希望这两个ZonedDateTime实例是平等的.

java datetime java-8 java-time

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

什么是Java 8中的"糖","desugar"术语?

我在Java 8中经常听说'糖化'和'贬低',这些术语是什么意思?他们是概念性的还是语法式的.

一些例子:

默认迭代循环重新发布到java

编辑中的句法糖观察.

java java-8 semantics

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