我有一个类,类似于下面的代码。它实现了Iterable<T>iterface,用于在其包含的数组上提供迭代功能。
我一直习惯于使用自己的简单迭代器来迭代数组。然而,我刚刚意识到,至少对于spliterators来说,您可以通过调用 来获得可接受的默认实现Arrays.spliterator(array)。普通Iterator<T>数组上是否有类似的默认实现T?
public class MyClass implements Iterable<ContainedClass>
{
...
private final ContainedClass[] array;
...
//
// INTERFACE: Iterable<ContainedClass>
//
@Override
public Iterator<ContainedClass> iterator() {
return ??? // I want to return a default implementation, not my own!
}
@Override
public Spliterator<ContainedClass> spliterator() {
return Arrays.spliterator(array);
}
}
Run Code Online (Sandbox Code Playgroud) I\xc2\xb4m 使用 Stream 并findFirst()返回Optional,但也有 \xc2\xb4s 有可能我的StreamMaybe 不会发出任何东西,所以我添加了orElse在底部添加了运算符。
问题是orElse不返回可选值,而是返回可选值的类类型findFirst。
def optional = categories.categories.stream()\n .filter { category -> category.name == selCategory }\n .map { category -> loadUniqueIds.call(category) }\n .map { UUIDs -> new JsonArray(UUIDs) }\n .findFirst().orElse{Optional.of(new JsonArray())}\n optional.get()\nRun Code Online (Sandbox Code Playgroud)\n所以我最终无法使用findFirst并且orElse。
我\xc2\xb4m在这里做错了什么?
\n谢谢
\n更新:
\n我最终删除了orElse之后findFirst并稍后检查可选的
optional.isPresent() ? optional.get(): new JsonArray()\nRun Code Online (Sandbox Code Playgroud)\n无论如何,如果有人有更好/优雅的解决方案,请告诉我。
\n问候。
\nJdk 1.8.0_82、Springboot 1.3.8 和 JPA。
我想插入由现有对象值组成的新行。
我只是打电话
List<LogSchemaFieldModel> newFields = Lists.newArrayList();
for(LogSchemaFieldModel f : fields){
newFields.add(new LogSchemaFieldModel(){{
setFieldName( f.getFieldName() );
setFieldType( f.getFieldType() );
setFieldOpt( Field.Mode.NULLABLE.toString() );
setDescription( f.getDescription() );
setSampleValue( f.getSampleValue() );
setCommon(true);
setRequired(null);
}});
}
repo.save(newFields);
Run Code Online (Sandbox Code Playgroud)
但它抛出了这个异常。
org.springframework.dao.InvalidDataAccessApiUsageException: Unknown entity: com......service.LogDefineService$6; nested exception is java.lang.IllegalArgumentException: Unknown entity: com......service.LogDefineService$6
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:384) ~[spring-orm-4.2.8.RELEASE.jar:4.2.8.RELEASE]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:227) ~[spring-orm-4.2.8.RELEASE.jar:4.2.8.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:436) ~[spring-orm-4.2.8.RELEASE.jar:4.2.8.RELEASE]
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59) ~[spring-tx-4.2.8.RELEASE.jar:4.2.8.RELEASE]
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213) ~[spring-tx-4.2.8.RELEASE.jar:4.2.8.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147) ~[spring-tx-4.2.8.RELEASE.jar:4.2.8.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.2.8.RELEASE.jar:4.2.8.RELEASE]
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:131) ~[spring-data-jpa-1.9.5.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.2.8.RELEASE.jar:4.2.8.RELEASE]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) ~[spring-aop-4.2.8.RELEASE.jar:4.2.8.RELEASE]
at …Run Code Online (Sandbox Code Playgroud) 1)我们的应用程序:Spring boot,Java 8
2)我们使用的参数:xms = 256 MB,xmx = 2 GB
我们已经看到,java8 应用程序的已用堆大小并没有在适当的时候缩小。
在启动 Spring Boot/Java 8 应用程序时,我们应该与上面的 #2 一起使用任何其他参数,以便 GC 可以做得更好吗?
感谢您的帮助!
我有一个 Fruit 对象列表,其中每个 Fruit 都有一个'name'和'desc'。此水果列表将包含'name'不同的重复项'desc'。i.e.
{"apple","its red"},{"banana","its yellow"},{"apple", "its hard"}
Run Code Online (Sandbox Code Playgroud)
现在,我想使用 Java 8 Streams API 迭代此 Fruits 列表,并将它们映射到 MAP 中,使得键为“name”且不得包含重复项。
输出应该是:
key - "apple", value - List of desc i.e. {"its red","its hard"}
key - "banana", value - {"its yellow"}
Run Code Online (Sandbox Code Playgroud)
请指导。
我在字符串中获取时间和偏移量。
时间采用 UTC 格式,我必须根据偏移量转换该时间,然后将其分配给一个Calendar对象。
问题是我正在使用类plusHours()方法OffsetDateTime。我得到相同的结果。
OffsetDateTime odtB = OffsetDateTime.parse( "2018-03-26T06:00:00Z" ) ;
odtB.plusHours(2);
System.out.println(odtB);
Run Code Online (Sandbox Code Playgroud)
例如,如果我的日期是"2018-03-26T06:00:00Z"并且偏移/时区值为“+02:00”,如何更改它以获取输出"2018-03-26T08:00:00Z"?
我有下面的代码
ThreadLocal<Map<String, Service<Request, Response>>> connectinonMapThread = new ThreadLocal<Map<String, Service<Request, Response>>>() {
@Override
protected Map<String, Service<Request, Response>> initialValue() {
return new HashMap<String, Service<Request, Response>>();
}
};
Run Code Online (Sandbox Code Playgroud)
我想使用 lambda 表达式来编写它,如下所示 -
ThreadLocal<Map<String, Service<Request, Response>>> connectinonMapThread2 = new ThreadLocal<Map<String, Service<Request, Response>>>(() -> new HashMap<String, Service<Request, Response>>());
Run Code Online (Sandbox Code Playgroud)
我尝试了另一种。
ThreadLocal<Map<String, Service<Request, Response>>> connectinonMapThread2 = initialValue() -> {
return new HashMap<String, Service<Request, Response>>();
};
Run Code Online (Sandbox Code Playgroud)
但我收到编译错误。但 IntelliJ Idea 建议这可以写成 lambda 表达式。
我确实有一个类CustomResponseEntityExceptionHandler扩展ResponseEntityExceptionHandler了两种方法,一种用于处理错误的格式,另一种用于请求资源(url)但不存在时。我想给用户一条自定义消息,而不是 Spring 默认的白标错误页面。我试图理解为什么我的handleResourceNotFoundException方法来自CustomResponseEntityExceptionHandler当请求不存在的 URI 时不调用,而是一直显示白标签错误页面。感谢您的帮助!
curl localhost:8080/doesnotexist\nRun Code Online (Sandbox Code Playgroud)\n\n这是我的CustomResponseEntityExceptionHandler
@ExceptionHandler(Exception.class)\npublic final ResponseEntity<ErrorDetails> handleAllWrongFormatExceptions(WrongFormatException ex,\n WebRequest request) {\n ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(true));\n return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);\n}\n\n@ExceptionHandler(ResourceNotFoundException.class)\npublic final ResponseEntity<ErrorDetails> handleResourceNotFoundException(ResourceNotFoundException ex,\n WebRequest request) {\n ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false));\n return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);\n}\nRun Code Online (Sandbox Code Playgroud)\n\n用于保存自定义错误详细信息的简单类
\n\npublic class ErrorDetails {\n\nprivate Date timestamp;\nprivate String message;\nprivate String details;\n\npublic ErrorDetails(Date timestamp, String message, String details) …Run Code Online (Sandbox Code Playgroud) 我有一个这样的对象:
@Data
@AllArgsConstructor
@NoArgsConstructor
class Person {
private String name;
private String lastName;
}
Run Code Online (Sandbox Code Playgroud)
还有一个,我们称之为:
@Data
@AllArgsConstructor
@NoArgsConstructor
class DBPerson {
private String name;
private String lastName;
}
Run Code Online (Sandbox Code Playgroud)
假设两个对象都有一个带有name和的构造函数lastName以及它们各自的 getter 和 setter,我正在使用lombok
List<DBPerson> dbPersons = new ArrayList();
dbPersons.add(new DBPerson("Harry", "Potter"));
dbPersons.add(new DBPerson("Hermione", "Granger"));
dbPersons.add(new DBPerson("Ronald", "Weasley"));
Run Code Online (Sandbox Code Playgroud)
我需要从 a 转换List<DBPerson>为List<Person>,所以我尝试了这种方式:
dbPersons.stream()
.map(DBPerson::getName)
.map(Person::new)
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
这显然给了我一个错误,new因为没有带有单个StringonPerson类的构造函数
我怎么能映射两个属性DBPerson来创建一个新的Person,然后将所有这些都收集到一个List<Person>?
我已经尝试过.forEach,但是我不确定它是否是最佳解决方案,所以如果有另一种使用 Stream …
我想打电话给cancel上CompletableFuture。
从文档看来:
如果尚未完成,则使用 CancellationException 完成此 CompletableFuture。尚未完成的从属 CompletableFutures 也将异常完成,此 CancellationException 会导致 CompletionException。
它应该异常地完成它们,这正是我所期望的,但相反,它会立即抛出 CancellationException。
这是一个示例代码
CompletableFuture<?> f = CompletableFuture.supplyAsync(() -> false);
f.cancel(true); // Line 7.
f.join();
Run Code Online (Sandbox Code Playgroud)
使用重现:https : //www.mycompiler.io/view/2v1ME4u
Exception in thread "main" java.util.concurrent.CancellationException
at java.base/java.util.concurrent.CompletableFuture.cancel(CompletableFuture.java:2396)
at Main.main(Main.java:7)
Run Code Online (Sandbox Code Playgroud)
7号线是f.cancel(true);线。
java concurrency java.util.concurrent java-8 completable-future
java-8 ×10
java ×6
java-stream ×3
arrays ×1
calendar ×1
concurrency ×1
datetime ×1
groovy ×1
hashmap ×1
iterator ×1
merge ×1
spring ×1
spring-boot ×1
spring-mvc ×1