标签: java-8

Clojure传感器与Java中的流中间操作具有相同的概念吗?

当我在Clojure中学习传感器时,它突然让我想起了他们提醒我的:Java 8流!

传感器是可组合的算法变换.它们独立于输入和输出源的上下文,并且仅根据单个元素指定转换的本质.

是不是一个数据结构,用于存储内容; 相反,它通过计算操作管道传递来自诸如数据结构,数组,生成器函数或I/O通道的源的元素.

Clojure的:

(def xf
  (comp
    (filter odd?)
    (map inc)
    (take 5)))

(println
  (transduce xf + (range 100)))  ; => 30
(println
  (into [] xf (range 100)))      ; => [2 4 6 8 10]
Run Code Online (Sandbox Code Playgroud)

Java的:

// Purposely using Function and boxed primitive streams (instead of
// UnaryOperator<LongStream>) in order to keep it general.
Function<Stream<Long>, Stream<Long>> xf =
        s -> s.filter(n -> n % 2L == 1L)
                .map(n -> n + 1L)
                .limit(5L);

System.out.println(
        xf.apply(LongStream.range(0L, …
Run Code Online (Sandbox Code Playgroud)

java clojure transducer java-8 java-stream

13
推荐指数
1
解决办法
698
查看次数

无法从TemporalAccessor获取OffsetDateTime

当我这样做

String datum = "20130419233512";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss").withZone(ZoneId.of("Europe/Berlin"));
OffsetDateTime datetime = OffsetDateTime.parse(datum, formatter);
Run Code Online (Sandbox Code Playgroud)

我得到以下异常:

    java.time.format.DateTimeParseException: Text '20130419233512' could not be parsed: 
Unable to obtain OffsetDateTime from TemporalAccessor: {InstantSeconds=1366407312},ISO,Europe/Berlin resolved 
to 2013-04-19T23:35:12 of type java.time.format.Parsed
Run Code Online (Sandbox Code Playgroud)

如何解析我的日期时间字符串,以便将其解释为始终来自"Europe/Berlin"时区?

java java-8 java-time

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

AtomicInteger.updateAndGet()和AtomicInteger.accumulateAndGet()之间是否存在任何功能差异?

是否存在AtomicInteger.accumulateAndGet()无法替换的场景AtomicInteger.updateAndGet(),或者仅仅是方法引用的便利?

这是一个简单的例子,我没有看到任何功能差异:

AtomicInteger i = new AtomicInteger();
i.accumulateAndGet(5, Math::max);
i.updateAndGet(x -> Math.max(x, 5));
Run Code Online (Sandbox Code Playgroud)

显然,同样也适用于getAndUpdate()getAndAccumulate().

java lambda atomic java-8 atomicinteger

13
推荐指数
1
解决办法
5151
查看次数

Java Lambda引用封闭对象:替换为私有静态类?

引用其封闭范围内的元素的Java lambda包含对其封闭对象的引用.一个人为的例子,lambda持有ref给MyClass:

class MyClass {
  final String foo = "foo";
  public Consumer<String> getFn() {
    return bar -> System.out.println(bar + foo);
  }
}
Run Code Online (Sandbox Code Playgroud)

如果lambda的寿命很长,这是有问题的; 然后我们得到一个长寿的MyClass引用,否则它会超出范围.在这里我们可以通过用私有静态类替换lambda来优化,这样我们只需要对我们需要的String进行引用,而不是对整个类:

class MyClass {

  private static class PrintConsumer implements Consumer<String> {

    String foo;

    PrintConsumer(String foo) {
      this.foo = foo;
    }

    @Override
    public void accept(String bar) {
      System.out.println(bar + foo);
    }
  }

  final String foo = "foo";

  public Consumer<String> getFn() {
    return new PrintConsumer(foo);
  }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,这是超级冗长的,并且破坏了我们从lambdas中封闭范围中使用(有效最终)变量获得的良好语法.这在技术上是最佳的吗?是否总是在良好的语法和保持ref超过必要的可能性之间进行权衡?

java lambda functional-programming java-8

13
推荐指数
1
解决办法
456
查看次数

如何使用Spring Data REST进行高级搜索?

我的任务是使用Spring Data REST进行高级搜索.我该如何实现它?

我设法做了一个简单的搜索方法,就像这样:

public interface ExampleRepository extends CrudRepository<Example, UUID>{

    @RestResource(path="searchByName", rel="searchByName")
    Example findByExampleName(@Param("example") String exampleName);

}
Run Code Online (Sandbox Code Playgroud)

如果我必须简单地去网址,这个例子很有效:

.../api/examples/search/searchByName?example=myExample
Run Code Online (Sandbox Code Playgroud)

但是,如果要搜索多个字段,我该怎么做?

例如,如果我的Example类有5个字段,那么我应该使用所有possibiles文件进行高级搜索?

考虑一下这个:

.../api/examples/search/searchByName?filed1=value1&field2=value2&field4=value4
Run Code Online (Sandbox Code Playgroud)

还有这个:

.../api/examples/search/searchByName?filed1=value1&field3=value3
Run Code Online (Sandbox Code Playgroud)

我需要做些什么才能以适当的方式实现此搜索?

谢谢.

java spring java-8 spring-data-rest

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

如何在Java 8 Lambdas中使用非final变量

如何在Java 8 lambda中使用非final变量.它抛出编译错误,说'在封闭范围中定义的局部变量日期必须是最终的或有效的最终'

我其实想要实现以下目标

public Integer getTotal(Date date1, Date date2) {
    if(date2 == null || a few more conditions) {
        date2 = someOtherDate;
    }
    return someList.stream().filter(filter based on date1 and date2).map(Mapping Function).reduce(Addition);
}
Run Code Online (Sandbox Code Playgroud)

我该如何实现这一目标?它会引发date2的编译错误.谢谢,

java lambda final java-8

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

在顺序排序的流中查找缺少的整数

假设我有一个清单

ArrayList<String> arr = new ArrayList(Arrays.asList("N1", "N2", "N3", "N5"));
Run Code Online (Sandbox Code Playgroud)

我怎么找到"N4",我的意思是,我怎么发现丢失的整数是4?

到目前为止我尝试过的

Integer missingID = arr.stream().map(p -> Integer.parseInt(p.substring(1))).sorted()
                .reduce((p1, p2) -> (p2 - p1) > 1 ? p1 + 1 : 0).get();
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为reduce在这种情况下不打算以我需要的方式工作,实际上,我不知道怎么做.如果没有丢失的数字,则必须是下一个"N6" - or just 6 -(在此示例中)

它必须使用java标准流的库,不使用第三方.

java java-8 java-stream

13
推荐指数
3
解决办法
2432
查看次数

将Array迭代转换为lambda表达式

我有下面的代码迭代Cookies重置名称匹配的cookieCookieSession.NAME

  Cookie[] cookies = httpServletRequest.getCookies();
        LOGGER.info("Clearing cookies on welcome page");
        if (cookies != null)
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(CookieSession.NAME)) {                      
                cookie.setValue(null);
                cookie.setMaxAge(0);
                cookie.setPath("/");
                httpServletResponse.addCookie(cookie);
              }
            }
Run Code Online (Sandbox Code Playgroud)

有人可以使用java 8 lambda表达式来简化它

java lambda java-8

13
推荐指数
4
解决办法
2722
查看次数

检查Optionals平等的便捷方法

我正在寻找一种更方便的方法来证明Optional值的相等性.

这是Oracle博客文章建议的内容:

Optional<USB> maybeUSB = ...; maybeUSB.filter(usb -> "3.0".equals(usb.getVersion())
                    .ifPresent(() -> System.out.println("ok"));
Run Code Online (Sandbox Code Playgroud)

恕我直言的结果是这样的

if (maybeUSB.filter(c -> "3.0".equals(c.getVersion())).isPresent()) {
   ...
}
Run Code Online (Sandbox Code Playgroud)

当然这是一个糟糕的例子,因为它比较了版本而不是USB本身的实例,但我认为它仍然可以证明我的观点.

这真的很棒吗?

没有

boolean presentAndEquals(Object)
Run Code Online (Sandbox Code Playgroud)

要么

boolean deepEquals(Object)
Run Code Online (Sandbox Code Playgroud)

我在这里错过了什么吗?

编辑:

我对Optionals.equals也不满意.我是否真的必须首先装箱一个物体才能立即拆箱并检查是否相等?

java optional java-8

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

Java 8中的方法参考

public class Car {

    private int maxSpeed;

    public Car(int maxSpeed) {
        this.maxSpeed = maxSpeed;
    }

    public int getMaxSpeed() {
        return maxSpeed;
    }
}
Run Code Online (Sandbox Code Playgroud)

我们可以按以下方式对汽车列表进行排序

    Car carX = new Car(155);
    Car carY = new Car(140);

    List<Car> cars = new ArrayList<>();
    cars.add(carX);
    cars.add(carY);

    cars.sort(Comparator.comparing(Car::getMaxSpeed));
Run Code Online (Sandbox Code Playgroud)

如果我们看到方法的签名Comparator.comparing,则输入参数类型为Function<? super T, ? extends U>

在上面的例子中,是如何Car::getMaxSpeed被转换为Function<? super T, ? extends U>而以下不编译?

  Function<Void, Integer> function = Car::getMaxSpeed;
Run Code Online (Sandbox Code Playgroud)

java lambda java-8 method-reference

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