有没有办法为流的每个元素创建 2 个不同的对象并最后收集它们?
例如,如果我有 aList<String> stringList并且有一个GoddClass带有默认值和 a 的类customConstructor,我想在一个流中创建 2 个对象并最后收集
stringList
.stream()
.map(GoddClass::new)
.addAnothrObject(GoddClass::customConstructor) // Not a valid line, Just to depict what is needed
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
一个流可能不是实现我正在尝试的目标的正确解决方案。但这个问题留给专家们来解答。
我有一个功能可以按 3 个整数字段对 pojo 列表进行排序。
目前我正在使用comparingInt()和thenComparingBy()。
但我可能会在两者之间得到一个空值。这会抛出一个NullPointerException.
为此,我想在末尾添加空值。Comparator.nullsLast()不适用于我的情况,因为我正在比较 3 个整数值。
有没有办法实现这一点......
我是一个完全的新手,所以我请你不要说太多脏话)
有一个集合(ArrayList)保存Student类的对象(<HashMap <Subject, Integer> rating, String name>)。我必须使用 Stream API 计算特定科目的平均分数。我尝试这样做:
sumOnSubjectInGroup = studentsInGroup.stream()
.filter(e -> e.getRating().entrySet().iterator().next().getKey().equals(subject))
.mapToInt(e -> e.getRating().entrySet().iterator().next().getValue())
.reduce(0, (x, y) -> x + y);
countMarkInGroup = (int) studentsInGroup.stream()
.filter(e -> e.getRating().entrySet().iterator().next().getKey().equals(subject))
.count();
return (double) sumOnSubjectInGroup / countMarkInGroup;
Run Code Online (Sandbox Code Playgroud)
其中 sumOnSubjectInGroup是所有学生的学科分数之和。 countMarkInGroup - 此类标记的数量。 StudentsInGroup是包含所有 Student 对象的集合。 getRating () - 返回一个 HashMap <Subject, Integer> 及其项目和评级列表。但显然我得到了错误的结果
我有三个 LocalDate(最后 3 天),对于每个日期,我想循环并执行一些操作:
StringBuilder result = "";
for (LocalDate currentDate = LocalDate.now(); currentDate.isAfter(LocalDate.now().minusDays(3)); currentDate = currentDate.minusDays(1)){
Page<User> users = userService.getAllUsersByRegistrationDate(currentDate);
String reportTable = reportService.getReportTable(users, tableTemplate);
result.append(reportTable);
}
Run Code Online (Sandbox Code Playgroud)
如何用 Stream API 替换此代码或提高可读性?
personList如果为空或过滤结果为空,以下将抛出异常:
Person b2cInwardAllocTxs = personList.stream()
.filter(x -> x.getName().equalsIgnoreCase("Alvin"))
.findFirst().get();
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
Exception: java.util.NoSuchElementException: No value present
Run Code Online (Sandbox Code Playgroud)
如何解决错误?
实际上,我只是希望它应该返回一个对象或null.
我有一个对象:
class Sample
{
String currency;
String amount;
}
Run Code Online (Sandbox Code Playgroud)
我想要一个输出映射,其中包含特定货币的所有对象的总和。
例子-
指针。我一直在使用以下代码,但它没有按我的预期工作。您可以使用此代码作为参考:
Map<String, Double> finalResult = samples
.stream()
.collect(Collectors.toMap(
Sample::getCurrency,
e -> e.getAmount()
.stream()
.sum()));
Run Code Online (Sandbox Code Playgroud) 我有这段代码:
userAvailableRoles.stream()
.peek(x-> x.setPets(userPets(roles, hasValidAccess)));
Run Code Online (Sandbox Code Playgroud)
但我有这个警告:
Warning:(86, 18) Result of 'Stream.peek()' is ignored
Run Code Online (Sandbox Code Playgroud) 我对 Java 流有点陌生,并遇到了以下问题。我尝试了该网站和各种文章中提到的许多内容,但无法修复它们,因此将问题发布在这里。
我正在我的应用程序中创建一个Map<String, Object>using JavaStreams,然后将值传递给Map带有重复项的keys,然后它会抛出以下错误:
java.lang.IllegalStateException: Duplicate key namespace:localName (attempted merging values [ONE] and [TWO])
at java.base/java.util.stream.Collectors.duplicateKeyException(Collectors.java:133)
Run Code Online (Sandbox Code Playgroud)
以下是引发此错误的方法:
public Map<String, Object> toMap() {
final Map<String, Object> map = new HashMap<>();
if (complex != null && complex.size() > 0) {
final Map<String, Object> complexMap = complex.stream()
.flatMap(c -> c.toMap().entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
map.put(namespacePrefix.concat(":").concat(localName), complexMap);
} else {
map.put(namespacePrefix.concat(":").concat(localName), text);
}
return map;
}
Run Code Online (Sandbox Code Playgroud)
我尝试制作Objectas ,List以便如果发现重复值,则将其添加到List如下所示的内容中:
List<Object> values = …Run Code Online (Sandbox Code Playgroud) 我有 2 个清单:
List<String> authorizedList ; // ["11","22","33"]
List<MySerial> serials; // [Myserial1,Myserial2,Myserial3] =>
Run Code Online (Sandbox Code Playgroud)
MySerial 是具有 2 个参数的对象,Myserial(String serial, String name)
我想使用流检查序列中的所有序列是否都在授权列表中,但我是新使用它的。
if (!serials.stream().map(MySerial::getSerial).anyMatch(authorizedList::equals)) {
throw new UnauthorizedException();
}
Run Code Online (Sandbox Code Playgroud)
但它总是抛出异常。
假设我们有一个包含字段的 person 类:
Class Person {
private String name;
private Integer id (this one is unique);
}
Run Code Online (Sandbox Code Playgroud)
然后我们有一个List<Person> people这样的:
['Jerry', 993]
['Tom', 3]
['Neal', 443]
['Jerry', 112]
['Shannon', 259]
['Shannon', 533]
Run Code Online (Sandbox Code Playgroud)
我怎样才能创建一个新List<Person> uniqueNames的,使其仅过滤唯一名称并保留该名称的最高 ID。
所以最终列表将如下所示:
['Jerry', 993]
['Tom', 3]
['Neal', 443]
['Shannon', 533]
Run Code Online (Sandbox Code Playgroud) java ×10
java-stream ×10
java-8 ×4
collections ×3
collectors ×2
comparator ×1
compare ×1
dictionary ×1
filtering ×1
int ×1
java-time ×1
maxby ×1