我有以下情况:我有一个LinkedHashMap <>,其中键类型是String,并且值类型各不相同:double,String,LinkedHashMap等。我试图从其中一个LinkedHashMaps值的键中提取值。是主地图的值。例如,我想从下面的代码中得到结果1(显然,这是一团糟,因为它甚至没有编译):
Map<String, Object> input = new HashMap<>();
input.put("a", "1234");
input.put("b", "2345");
input.put("c", "3456");
input.put("d", new HashMap<String, String>());
HashMap<String, Object> input2 = (HashMap<String, Object>)(input.get("d"));
input2.put("d1", 1);
input2.put("d2", 2);
Optional<Integer> result = input.entrySet().stream()
.filter(e -> e.getKey().equals("d"))
.map(Map.Entry::getValue)
.filter(e -> e.getKey().equals("d1"))
.findFirst();
Run Code Online (Sandbox Code Playgroud)
我哪里出错了,当然,获得结果的最佳方法是什么?
谢谢。
我有一种情况,我希望特定类型的记录实例只能使用同一包内单独类中的工厂方法创建。这样做的原因是因为在创建记录之前我需要执行大量的验证。
记录旨在成为其验证字段的哑数据载体,但验证不能在记录的构造函数中进行,因为我们需要访问一些精心设计的验证器对象才能实际执行验证。
由于将验证器对象传递给记录构造函数意味着它们将构成记录状态的一部分,这意味着我们不能使用记录构造函数来执行记录的验证。
因此,我将验证提取到它自己的工厂中并编写了如下代码(工厂类和同一包中的记录):
package some.package;
// imports.....
@Component
class SomeRecordFactory {
private final SomeValidator someValidator;
private final SomeOtherValidator someOtherValidator;
// Rest of the fields
// ....
// constructor
// ....
public SomeRecord create(...) {
someValidator.validate(....);
someOtherValidator.validate(....);
// .... other validation
return new SomeRecord(...);
}
}
Run Code Online (Sandbox Code Playgroud)
package some.package;
public record SomeRecord(...) {
/* package-private */ SomeRecord {
}
}
Run Code Online (Sandbox Code Playgroud)
无论出于何种原因,上述内容不适用于 IntelliJ 抱怨:
Compact constructor access level cannot be more restrictive than the record access level (public)
Run Code Online (Sandbox Code Playgroud)
我可以通过使用普通类(允许使用单个包私有构造函数)来避免这个问题,但希望更准确地将数据建模为记录。
为什么记录存在此限制?未来是否有取消此限制的计划?
这不是我的问题的重复.我检查了它,它更多的是关于内部匿名类.
我对Lambda表达式很好奇并测试了以下内容:
第一个结果并不令人惊讶,因为我不知道我会想出什么:
final int NUMBER_OF_LIST_INDEXES = 10_000;
List<String> myList = new ArrayList<>();
String[] myWords = "Testing Lamba expressions with this String array".split(" ");
for (int i = 0 ; i < NUMBER_OF_LIST_INDEXES ; i++){
myList.add(myWords[i%6]);
}
long time = System.currentTimeMillis();
// BOTH TESTS WERE RUN SEPARATELY OF COURSE
// PUT THE UNUSED ONE IN COMMENTS WHEN THE OTHER WAS WORKING
// 250 milliseconds for the Lambda Expression
myList.removeIf(x -> x.contains("s"));
// 16 milliseconds for the traditional Loop …Run Code Online (Sandbox Code Playgroud) 我正在寻找一种非阻塞的方式来汇总的流CompleteableFuture<BigDecimal>。
我已经找到与之密切相关的问题的话题,像这样。但不幸的是,我确实将其BigDecimal打包到CompleteableFuture中,因此我需要首先等待完成。最后,我想获得另一个CompleteableFuture,包含完成后流中所有期货的总和。
编辑: 实际上我确实设法找到以下解决方案:
Stream<CompletableFuture<BigDecimal>> lotOfWork;
CompletableFuture.supplyAsync(() -> lotOfWork.map(CompletableFuture::join)
.reduce(
BigDecimal.valueOf(0.0),
BigDecimal::add
)
);
Run Code Online (Sandbox Code Playgroud)
但是,由于这没有使用任何CompletionStage方法,因此我很确定有更好的方法来完成此工作。
使用java.util.regex提取子字符串,我发现自己实现了相同的代码模式,以解决对的调用:
Pattern p = Pattern.compile(pattern); // can be static final
Matcher m = p.matcher(input);
if (m.find()) { // or m.matches()
foo(m.group(x));
} else {
...
}
Run Code Online (Sandbox Code Playgroud)
是否有功能扩展或流行的库(番石榴/ apache通用),避免了不必要的,容易出错的局部变量,例如:
Pattern p = Pattern.compile(pattern); // can be static final
p.matchedGroup(input, x) // return Optional<String>
.map(group -> foo(group))
.orElse(...);
Run Code Online (Sandbox Code Playgroud)
以及一系列匹配结果,例如:
Pattern p = Pattern.compile(pattern);
p.findMatches(input)
.map((MatchResult mr) -> {
mr.groupsIfPresent(x).map(g -> foo(g)).orElse(...)
})
.findFirst();
Run Code Online (Sandbox Code Playgroud)
似乎Java8中唯一的功能性添加是,.splitAsStream()但是仅在尝试拆分匹配项时才有用。
给定以下 Java 8 流:
scheduleService.list().stream()
.filter(Schedule::getEnabled)
.filter(this::runnable)
.flatMap(s -> s.getJobs().stream())
// .doSomethingArbitrary(System.out.println("A single message. The total number of
// elements in the stream after filtering is " + this::count))
.forEach(this::invoke);
Run Code Online (Sandbox Code Playgroud)
将过滤应用于流并应用第一个终端操作后,如果流为空,我想记录一条调试消息,或者如果不是,则对流invoke中的每个元素调用该方法。这可能吗?
查看 的实现Stream#toList,我只是注意到它看起来是多么复杂和次优。
就像上面的 javadoc 中提到的那样default,大多数实现都没有使用这个实现Stream,但是,在我看来,它本来可以是其他的。
/**
* Accumulates the elements of this stream into a {@code List}. The elements in
* the list will be in this stream's encounter order, if one exists. The returned List
* is unmodifiable; calls to any mutator method will always cause
* {@code UnsupportedOperationException} to be thrown. There are no
* guarantees on the implementation type or serializability of the returned List.
*
* <p>The returned instance …Run Code Online (Sandbox Code Playgroud) 当我们在 Java 中使用类时,为每个类字段/方法添加 JavaDoc/注释非常简单:
class Product {
//Product unique identifier
private int id;
}
Run Code Online (Sandbox Code Playgroud)
如果我们将这些类迁移到 Java 记录,则不清楚在这种情况下编写注释/JavaDocs 的最佳实践是什么:
record Product(int id, String name, double price) {
}
Run Code Online (Sandbox Code Playgroud)
因为现在所有字段都在一行中声明。
在我的火电视应用我使用的是recyclerview用horizontal layout.
滚动与dpad工作和项目正在获得关注.
但是,当我按住按钮时,它会非常快速地滚动,因为许多keydown事件被触发,并且项目正在失去焦点而且不可能再滚动,因为Textview我的recyclerview上方的另一个正在获得焦点.
它看起来像一个bug.这有什么解决方法吗?
我有以下地图:
{21=0, 22=2, 11=0, 12=0}
{21=3, 22=0, 11=6, 12=3}
{21=6, 22=0, 11=7, 12=0}
{21=5, 22=7, 11=9, 12=1}
Run Code Online (Sandbox Code Playgroud)
以下代码返回这些映射:
for (Chrom t: obj.getChroms) {
Map<Integer, Integer> result = t.getExecutionCount();
}
Run Code Online (Sandbox Code Playgroud)
该方法getExecutionCount()返回单个地图。对于上面给出的示例,我有四个色度,其中每个色度将返回一个图。
我想分别汇总每个键的值,以便最终结果将是:
21 = 14
22 = 9
11 = 22
12 = 4
Run Code Online (Sandbox Code Playgroud)
是否可以使用流来做到这一点?如果没有,我该怎么办?
java ×9
java-16 ×3
java-8 ×3
java-stream ×3
java-record ×2
android ×1
asynchronous ×1
for-loop ×1
java-14 ×1
java-9 ×1
lambda ×1
performance ×1
regex ×1