我对 Java 8 中的流很陌生,所以我的方法可能是错误的。
我有 2 个对象如下
object1 {
BigDecimal amount;
Code1 code1;
Code2 code2;
Code3 code3;
String desc;
}
object2 {
BigDecimal amount;
Code1 code1;
Code2 code2;
Code3 code3;
}
Run Code Online (Sandbox Code Playgroud)
所以我想收集 code1 && code2 && code3 相同的所有 object1,然后将数量相加将其添加到 object2 列表中。
我没有代码来做到这一点......我想编写一个代码来完成这项工作我正在尝试从http://docs.oracle.com/javase/tutorial/collections/interfaces/map.html实现一些东西
或者按部门计算所有工资的总和:
// Compute sum of salaries by department
Map<Department, Integer> totalByDept = employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment,
Collectors.summingInt(Employee::getSalary)));
Run Code Online (Sandbox Code Playgroud) 我有一个字符串流:
Stream<String> stream = ...;
我想使用创建一个字符串
stream.collect(Collectors.joining(',', '[', ']'))
如果流不包含任何元素,我只想返回“无字符串”。
我注意到该String java.util.stream.Stream.collect(Collector<? super String, ?, String> collector)
方法采用 java.util.stream.Collector<T, A, R> 类型的参数
对于我的项目,我在很多地方都需要这个功能,所以我需要一个实现Collector接口的类。
我知道这可以通过 Stream to a List 然后检查 List.size() == 0 来完成?如果需要,然后再次将列表转换为流。
List<String> list = stream.collect(Collectors.toList());
if (list.size() == 0) {
return "No Strings";
}
return list.stream().collect(Collectors.joining(",", "[", "]"));`
Run Code Online (Sandbox Code Playgroud)
List emptyList<String> = new ArrayList<>; System.out.println(emptyList.stream().collect(Collectors.joining(",", "[", "]")));
[]
No Strings
之前已经回答过类似的问题,但是我仍然无法弄清楚我的分组和平均方法有什么问题。
我曾尝试多个返回值的组合一样Map<Long, Double>,Map<Long, List<Double>,Map<Long, Map<Long, Double>>,Map<Long, Map<Long, List<Double>>>和那些没有修复错误的IntelliJ我抛出的:“非静态方法不能从静态上下文中引用”。此刻,我觉得我只是在盲目猜测。那么,谁能给我一些关于如何确定正确的回报类型的见解?谢谢!
方法:
public static <T> Map<Long, Double> findAverageInEpochGroup(List<Answer> values, ToIntFunction<? super T> fn) {
return values.stream()
.collect(Collectors.groupingBy(Answer::getCreation_date, Collectors.averagingInt(fn)));
}
Run Code Online (Sandbox Code Playgroud)
答案类别:
@Getter
@Setter
@Builder
public class Answer {
private int view_count;
private int answer_count;
private int score;
private long creation_date;
}
Run Code Online (Sandbox Code Playgroud) 在处理 Java 流时,我们可以使用收集器来生成诸如流之类的集合。
例如,这里我们制作了一个Month枚举对象的流,并为每个对象生成一个String保存月份的本地化名称的流。我们通过调用 将结果收集到 a Listof 类型中。StringCollectors.toList()
List < String > monthNames =
Arrays
.stream( Month.values() )
.map( month -> month.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) )
.collect( Collectors.toList() )
;
Run Code Online (Sandbox Code Playgroud)
monthNames.toString(): [janvier, février, mars, avril, mai, juin, juillet, août, septembre, octobre, novembre, décembre]
为了使该列表不可修改,我们可以List.copyOf在 Java 10 及更高版本中调用。
List < String > monthNamesUnmod = List.copyOf( monthNames );
Run Code Online (Sandbox Code Playgroud)
? 有没有办法让带有收集器的流生成不可修改的列表,而我不需要包装对 的调用List.copyOf?
我有两个清单;
val keys: List<String> = listOf("key1", "key2", "key3"...)
val values: List<String> = listOf("value1", "value2", "value3"...)
Run Code Online (Sandbox Code Playgroud)
我怎样才能将它们合二为一List<Hashmap<Key,Value>>?喜欢;
println(List<Hashmap<Key,Value>>): [[key1 = value1], [key2 = value2], [key3 = value3]...
有没有办法根据属性的值将对象列表转换为字符串列表?我有一个实体标签
public class Tag {
private int tagID;
private String description;
}
Run Code Online (Sandbox Code Playgroud)
我得到一个带有 ID 和描述的标签列表:
[Tag [tagID=1, description=121], Tag [tagID=1, description=244], Tag [tagID=1, description=331], Tag [tagID=2, description=244], Tag [tagID=2, description=122]]
Run Code Online (Sandbox Code Playgroud)
我需要的是:
List<String> output = ["121,244,331", "244,122"]
Run Code Online (Sandbox Code Playgroud)
到目前为止,我把这个放在一起:
String description = tags.stream().map(Tag::getDescription).collect(Collectors.joining( ";" ));
Run Code Online (Sandbox Code Playgroud)
输出一个标签的结果
String description = "121,244,331"
Run Code Online (Sandbox Code Playgroud)
当然,我可以通过循环运行它并将结果附加到数组中,但我想知道是否有更优雅的方式 - 甚至是单行?
我想从 Bean 列表生成一个字符串列表,包括 id 和外部 id。
public class User {
private String id;
private List<String> externalIds;
}
Run Code Online (Sandbox Code Playgroud)
我使用下面的代码得到了它,但这里我需要进行两次流。
List<User> references = new ArrayList();
Stream.concat(references.stream().map(User::getId),
references.stream().map(User::getExternalIds).flatMap(Collection::stream))
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来重写这段代码?
我正在使用 java 11,使用 sts IDE,我可以从 IDE 编译并运行 springboot 应用程序,但是当我使用 mvn 从命令行编译它时
mvn clean verify
Run Code Online (Sandbox Code Playgroud)
我收到这个错误
cannot find symbol [ERROR] symbol: method toList()
Run Code Online (Sandbox Code Playgroud)
代码片段是
......
......
return addressRepository.getAddressesBySystemUserId(systemUserId).stream().map(e -> {
AddressDto dto = null;
dto = AddressMapper.mapAddressToAddressDto(e);
return dto;
}).toList();
......
Run Code Online (Sandbox Code Playgroud)
pom 文件的片段
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
Run Code Online (Sandbox Code Playgroud) 我有一个接收收集器的方法。收集器应该合并传入列表:
reducing(Lists.newArrayList(), (container, list) -> {
container.addAll(list);
return container;
})
Run Code Online (Sandbox Code Playgroud)
这对我来说似乎是一个非常常见的场景,我相信 Java 自己的收集器应该有一些东西来涵盖这个用例,但我不记得是什么了。再说了,我还想让它回来ImmutableList。
我有这样的代码,它应该Map从整数数组创建一个。键代表位数。
public static Map<Integer, List<String>> groupByDigitNumbersArray(int[] x) {
return Arrays.stream(x) // array to stream
.filter(n -> n >= 0) // filter negative numbers
.collect(Collectors.groupingBy(n -> Integer.toString((Integer) n).length(), // group by number of digits
Collectors.mapping(d -> (d % 2 == 0 ? "e" : "o") + d,
Collectors.toList()))); // if even e odd o add to list
}
Run Code Online (Sandbox Code Playgroud)
问题与 一致mapping()。我收到错误:
public static Map<Integer, List<String>> groupByDigitNumbersArray(int[] x) {
return Arrays.stream(x) // array to stream
.filter(n …Run Code Online (Sandbox Code Playgroud) collectors ×10
java ×8
java-stream ×8
dictionary ×2
list ×2
arrays ×1
grouping ×1
java-8 ×1
kotlin ×1
unmodifiable ×1