标签: java-8

Java 8流:从一个列表中查找与基于另一个列表中的值计算的条件匹配的项

有两个类和两个相应的列表:

class Click {
   long campaignId;
   Date date;
}

class Campaign {
   long campaignId;
   Date start;
   Date end;
   String type;
}

List<Click> clicks = ..;
List<Campaign> campaigns = ..;
Run Code Online (Sandbox Code Playgroud)

并希望找到所有Clickclicks:

  1. 列表中有相应Campaigncampaigns,即Campaign具有相同的campaignIdAND

  2. Campaigntype="预期"和

  3. Campaigns.start< click.date<Campaigns.end

到目前为止,我有以下实现(这对我来说似乎令人困惑和复杂):

clicks.
        stream().
        filter(click -> campaigns.stream().anyMatch(
                campaign -> campaign.getCampaignType().equals("prospecting") &&
                        campaign.getCampaignId().equals(click.getCampaignId()) &&
                        campaign.getStart().after(click.getDate()) &&
                        campaign.getEnd().before(click.getDate()))).
        collect(toList());
Run Code Online (Sandbox Code Playgroud)

我想知道这个问题是否有更简单的解决方案.

java java-8 java-stream

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

如何以毫秒为单位返回LocalDate.now()?

我现在创建日期:

ZoneId gmt = ZoneId.of("GMT");
LocalDateTime localDateTime = LocalDateTime.now();
LocalDate localDateNow = localDateTime.toLocalDate();
Run Code Online (Sandbox Code Playgroud)

然后我希望以毫秒为单位返回此日期:

localDateNow.atStartOfDay(gmt) - 22.08.2017
localDateNow.atStartOfDay(gmt).toEpochSecond(); - 1503360000 (18.01.70)
Run Code Online (Sandbox Code Playgroud)

我怎么能LocalDate.now()在几毫秒内返回?

timestamp java-8 java-time localdate

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

保存到MySQL数据库时如何阻止LocalDate更改

使用JPA CriteriaBuilder API 将LocalDate字段(例如“ 2017-09-27”)保存到mySQL Date列时,结果会有所不同(例如“ 2017-09-26”)。

我已经验证我的数据库的时区设置为UTC SELECT TIMEDIFF(NOW(), UTC_TIMESTAMP),结果是“ 00:00:00”。

我在本地测试这一点,我有GMT + 2的时区,所以我怀疑的是,当发生转换,从LocalDateDate,被扣除生产要求的日期之前的日期1天第2小时(假设LocalDate领域,如没有时间信息的结果将被视为00:00:00。

在这种情况下保存LocalDates的最佳方法是什么?我是否应该按照这里的建议/sf/answers/2082610281/并将所有LocalDate字段显式设置为UTC或类似内容?

我进行了测试,以查看将它们转换为代码时会发生什么,并得到以下结果:

Date convertedDate = Date.valueOf(localDate);
Run Code Online (Sandbox Code Playgroud)

转换结果

编辑

这是我用来检索数据的代码示例,其中也发生了奇数日期更改。如果我要求提供数据2017-06-27,我将收到的结果2017-06-26

CriteriaBuilder criteriaBuilder = sessionFactory.getCriteriaBuilder();
CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(HorseAndTrailerRequest.class);
Root<HorseAndTrailerRequest> criteria = criteriaQuery.from(HorseAndTrailerRequest.class);

ParameterExpression<LocalDate> effectiveDateParameter = criteriaBuilder.parameter(LocalDate.class);
    criteriaQuery.select(criteria)
            .where(
                    criteriaBuilder.equal(criteria.get("effectiveDate"), effectiveDateParameter)
            );

TypedQuery<HorseAndTrailerRequest> query = sessionFactory.getCurrentSession().createQuery(criteriaQuery);
query.setParameter(effectiveDateParameter, date);
return query.getResultList();
Run Code Online (Sandbox Code Playgroud)

mysql jpa-2.0 java-8 hibernate-5.x localdate

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

创建已完成的CompletableFuture <Void>的正确方法是什么

我在java 8中使用Completable future我想编写一个方法,根据接收到的参数,并行运行带有副作用的多个任务然后返回它们的"组合"未来(使用CompletableFuture.allOf()),或者什么都不做并返回一个已经完成的未来.

但是,allOf返回一个CompletableFuture<Void>:

public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs)
Run Code Online (Sandbox Code Playgroud)

并且创建已经完成的未来的唯一方法就是使用completedFuture(),它需要一个值:

public static <U> CompletableFuture<U> completedFuture(U value)
Run Code Online (Sandbox Code Playgroud)

返回已使用给定值完成的新CompletableFuture.

并且Void是不可实现的,所以我需要另一种方法来创建已经完成的类型未来CompletableFuture<Void>.

做这个的最好方式是什么?

java concurrency java-8 completable-future

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

Java Lambda到比较器转换 - 中间表示

我试图理解Comparator.comparing函数是如何工作的.我创建了自己的比较方法来理解它.

private static <T,U extends Comparable<U>> Comparator<T> comparing(Function<T,U> f) {
    BiFunction<T,T,Integer> bfun = (T a, T b) -> f.apply(a).compareTo(f.apply(b));
    return (Comparator<T>) bfun;
}
Run Code Online (Sandbox Code Playgroud)

此函数的最后一行抛出异常.

但是,如果我将此功能更改为

private static <T,U extends Comparable<U>> Comparator<T> comparing(Function<T,U> f) {
    return (T a, T b) -> f.apply(a).compareTo(f.apply(b));
}
Run Code Online (Sandbox Code Playgroud)

它按预期工作得很好.

第二次尝试使用的中间功能接口是什么,能够将lambda转换为Comparator

java lambda comparator java-8 functional-interface

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

Java 8从HashMap中提取非null和非空值

让我们考虑一下 HashMap

HashMap<String, String> map = new HashMap<String, String>();
Run Code Online (Sandbox Code Playgroud)

我在地图中有值

map.put("model", "test");
Run Code Online (Sandbox Code Playgroud)

目前,如果我想从我正在做的地图中获取价值

if(map!=null){
 if(map.get("model")!=null && !map.get("model").isEmpty()){
   //some logic
 }
}
Run Code Online (Sandbox Code Playgroud)

通过使用Optional或Lambdas来实现上述条件,Java 8中是否有更好的方法?

java dictionary optional java-8

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

以Java 8方式检查对象中包含的null对象和null值

如何使用Optionals将此函数重写为更多Java 8?或者我应该保持原样?

public void setMemory(ArrayList<Integer> memory) {
    if (memory == null)
        throw new IllegalArgumentException("ERROR: memory object can't be null.");
    if (memory.contains(null))
        throw new IllegalArgumentException("ERROR: memory object can't contain null value.");

    this.memory = memory;
}
Run Code Online (Sandbox Code Playgroud)

java arraylist optional java-8

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

Dropwizard Metric Annotations @Timed无效

我正在尝试使用@Timed(http://metrics.dropwizard.io/3.1.0/apidocs/com/codahale/metrics/annotation/package-summary.html)等注释自动将指标发布到我的MetricRegistry .

这不是开箱即用的.在搜索问题时,我发现了Codahale Metrics:在普通Java使用@Timed指标注释,其中提到了这个工作的唯一方法是使用aspectj.我将此添加到我的项目中,但仍未在MetricRegistry中看到我的指标.

这是我的pom文件.我添加了一个librato库,它加载了com.codahale.metrics:metrics-annotation.

<dependency>
  <groupId>io.astefanutti.metrics.aspectj</groupId>
  <artifactId>metrics-aspectj</artifactId>
  <version>${metrics-aspectj.version}</version>
</dependency>
<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjrt</artifactId>
  <version>1.8.10</version>
</dependency>

  <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>aspectj-maven-plugin</artifactId>
    <version>1.7</version>
    <configuration>
      <showWeaveInfo>true</showWeaveInfo>
      <source>1.8</source>
      <target>1.8</target>
      <complianceLevel>1.8</complianceLevel>
      <encoding>UTF-8</encoding>
      <verbose>true</verbose>
      <aspectLibraries>
        <aspectLibrary>
          <groupId>io.astefanutti.metrics.aspectj</groupId>
          <artifactId>metrics-aspectj</artifactId>
        </aspectLibrary>
      </aspectLibraries>
    </configuration>
    <executions>
      <execution>
        <phase>process-sources</phase>
        <goals>
          <goal>compile</goal>
          <goal>test-compile</goal>
        </goals>
      </execution>
    </executions>
  </plugin>

<dependency>
  <groupId>com.librato.metrics</groupId>
  <artifactId>metrics-librato</artifactId>
  <version>${metrics-librato.version}</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

这就是我尝试使用指标的方式

@Metrics(registry = "default") // this.metricRegistry is default
public class Foo {
    @Inject
    private MetricRegistry metricRegistry;
    ...

    @Metered(name = "meterName")
    public void bar() { …
Run Code Online (Sandbox Code Playgroud)

java aspectj java-8 dropwizard librato

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

可选Java 8中flatMap的签名

oracle文档中,它似乎是

<U> Optional<U> flatMap(Function<? super T,Optional<U>> mapper)
Run Code Online (Sandbox Code Playgroud)

对于mappera Function,它使参数反变,但不使返回类型协变.我想知道是否mapper可以(应该)

Function<? super T,Optional<? extends U>>
Run Code Online (Sandbox Code Playgroud)

要么

Function<? super T, ? extends Optional<? extends U>>
Run Code Online (Sandbox Code Playgroud)

java optional java-8

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

如何在Java 8和ModelMapper中使用显式映射?

我通过官方文档http://modelmapper.org/getting-started/学习如何使用ModelMapper

有使用java 8进行显式映射的代码示例

modelMapper.addMappings(mapper -> {
  mapper.map(src -> src.getBillingAddress().getStreet(),
      Destination::setBillingStreet);
  mapper.map(src -> src.getBillingAddress().getCity(),
      Destination::setBillingCity);
});
Run Code Online (Sandbox Code Playgroud)

如何正确使用此代码?当我在IDE中键入此代码段时,IDE会显示消息"无法解析方法映射" 在此输入图像描述

java java-8 modelmapper

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