我有一群List以薪水为特征的员工。为什么这段代码不起作用?
String joined = employees.stream().collect(
Collectors.summingInt(Employee::getSalary),
Collectors.maxBy(Comparator.comparing(Employee::getSalary)),
Collectors.minBy(Comparator.comparing(Employee::getSalary)),
Collectors.averagingLong((Employee e) ->e.getSalary() * 2),
Collectors.counting(),
Collectors.joining(", "));
Run Code Online (Sandbox Code Playgroud)
我正在使用一套收集器。
编码时使用java流显示错误
Optional.ofNullable(product.getStudents())
.orElseGet(Collections.emptyList())
.stream().map(x->x.getId)
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
此代码显示以下错误 错误
不兼容的类型,必需的供应商> 但空列表被干扰到 List : 不存在 T 类型变量的实例,因此 List 符合供应商>
但是如果我替换Collections.emptyList()WITH Collections::emptyList
It 就完美了。
Collections.emptyList() 与 Collections::emptyList 有什么区别?
考虑以下代码:
public class StreamDemo {
public static void main(String[] args) {
StreamObject obj = new StreamObject();
obj.setName("mystream");
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
list.parallelStream().forEach(l -> {
obj.setId(l);
System.out.println(obj + Thread.currentThread().getName());
});
}
static public class StreamObject {
private String name;
private Integer id;
// getters, setters, toString()
}
}
Run Code Online (Sandbox Code Playgroud)
当使用 java 11 编译并运行时,它返回以下内容:
StreamObject{name='mystream', id=4}ForkJoinPool.commonPool-worker-23
StreamObject{name='mystream', id=4}main
StreamObject{name='mystream', id=4}ForkJoinPool.commonPool-worker-9
StreamObject{name='mystream', id=4}ForkJoinPool.commonPool-worker-5
StreamObject{name='mystream', id=4}ForkJoinPool.commonPool-worker-19
Run Code Online (Sandbox Code Playgroud)
但对于 java 1.8,它返回不同的结果:
StreamObject{name='mystream', id=3}main
StreamObject{name='mystream', id=5}ForkJoinPool.commonPool-worker-2
StreamObject{name='mystream', id=2}ForkJoinPool.commonPool-worker-9
StreamObject{name='mystream', id=1}ForkJoinPool.commonPool-worker-11
StreamObject{name='mystream', id=4}ForkJoinPool.commonPool-worker-4
Run Code Online (Sandbox Code Playgroud)
为什么结果不同?
我有一个这样的清单
[A-Apple.txt,B-Ball.txt,A-Axe.txt,B-Box.txt]
Run Code Online (Sandbox Code Playgroud)
由此我想创建一个如下所示的地图:
{A=[A-Apple.txt,A-Axe.txt], B= [B-Ball.txt, B-Box.txt]
Run Code Online (Sandbox Code Playgroud)
我试过
Map<String,List<String>> inputMap = new HashMap<>();
inputFCSequenceFileList.forEach(value ->{
List newList = new ArrayList();
newList.add(value);
inputMap.put(value.split("-")[0], newList);
}
);
Run Code Online (Sandbox Code Playgroud)
但没有得到预期值。我只得到最后一个元素。如果我将列表创建移到 foreach 循环之外,那么我将获得所有值。
我正在对对象列表进行分组,如下面的代码所示
Map<String, List<InventoryAdjustmentsModel>> buildDrawNumEquipmentMap = equipmentsAndCargoDetails.stream().
collect(Collectors.groupingBy(InventoryAdjustmentsModel :: getBuildDrawNum));
Run Code Online (Sandbox Code Playgroud)
现在我知道所有键的值只有一个元素,所以我怎样才能将它减少到只有一个元素
Map<String, InventoryAdjustmentsModel>
Run Code Online (Sandbox Code Playgroud)
而不是必须遍历或获取所有键的第 0 个元素。
我试图了解减少累加器的操作:在下面的例子中
List<String> letters = Arrays.asList("a","bb","ccc");
String result123 = letters
.stream()
.reduce((partialString, element) ->
partialString.length() < element.length()
? partialString
: element
).get();
System.out.println(result123);
Run Code Online (Sandbox Code Playgroud)
partialString 是否初始化为空字符串?由于它是一个折叠操作,我认为该操作应该导致空字符串但它的打印"a". 有人可以解释一下这个累加器是如何工作的吗?
我必须将 ArrayList 的每个元素复制 n 次。我试图通过以下方式做到这一点:
List<String> elements = new ArrayList();
elements.add("1");
elements.add("2");
elements.add("3");
List<String> newList = new ArrayList();
for(int i = 0; i < elements.size(); i++){
newList = Collections
.nCopies(10, elements.get(i));
}
Run Code Online (Sandbox Code Playgroud)
但它只重复元素 List 的最后一个元素 10 次
基本上我想要做的是用java 8特性编写一个像下面这样的for循环,
private String createHashCode() {
for (int i = 0; i < MAX_TRY; i++) {
final String hashCode = createRandomString();
if (!ishashCodeExistence(hashCode)) {
return hashCode;
}
}
throw new HashCodeCollisonException();
}
Run Code Online (Sandbox Code Playgroud)
我试过的是;
private String createHashCode() {
IntStream.range(0, MAX_TRY).forEach($ -> {
final String hashCode = createRandomString();
if (!ishashCodeExistence(hashCode)) {
return hashCode;
}
});
throw new HashCodeCollisonException();
}
Run Code Online (Sandbox Code Playgroud)
但是,lambda 中的 foreach 方法返回 void,因此我无法返回字符串。
有什么方法可以编写我的方法而不是使用普通的 for 循环?
相对较新到Java 8,我想知道为什么它允许第一个变体(merge功能不是必要的)Collectors.toMap()一起工作时List:
static <T,K,U> Collector<T,?,Map<K,U>> toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper)
Run Code Online (Sandbox Code Playgroud)
AList允许完全重复的值。想象一个用例,其中开发人员用于stream转换List为MapJava 8 将 RUNTIME 公开为:
Exception in thread "main" java.lang.IllegalStateException: Duplicate key ...
Run Code Online (Sandbox Code Playgroud)
不应该要求在编译时捕获这种情况吗?AFAIK,哈希图用于在放置Entry重复项时简单地替换旧的key。如果开发人员确定数据中存在重复值并希望将此异常作为警告处理,他会不会首先使用Set代替List?例如。:-
public class Employee{
public String name;
public String surname;
public Employee(String firstname, String secondName) {
this.name=firstname;this.surname=secondName;
}
public boolean equals(Object o){
return (o instanceof Employee) && ((Employee)o).name.equals(this.name) …Run Code Online (Sandbox Code Playgroud) 我知道 SO 上有多个问题与这个问题非常相似,但我找不到我希望得到的解决方案。
我的用例在这里非常简单。我有一个 Optional 对象,如果 Optional 中的对象存在,我想从 Optiona 对象返回一个值。例如,我想做这样的事情:
private String getUserName(String id) {
// this doesn't work
return fetchUser(id).ifPresent(user -> user.getName()).orElse("DEFAULT_NAME");
}
private Optional<User> fetchUser(String id) {
try {
return Optional.ofNullable(searchUser(id));
} catch (Exception e) {
LOGGER.error("User not found with id {}", id);
return Optional.empty();
}
}
Run Code Online (Sandbox Code Playgroud)
我当然试图避免if这里的块,我也知道它ifPresent需要 a Consumer,因此里面的任何东西ifPresent都不会返回任何值。但是有没有办法像上面那样以更优雅的方式实现这一点。解决这个问题的方法当然是重新编写如下代码:
private String getUserName(String id) {
// return fetchUser(id).ifPresent(user -> user.getName()).orElse("DEFAULT_NAME");
Optional<User> user = fetchUser(id);
if(user.isPresent()) {
return user.get().getName();
} else { …Run Code Online (Sandbox Code Playgroud) java ×10
java-8 ×10
java-stream ×5
collectors ×2
hashmap ×2
arraylist ×1
for-loop ×1
java-11 ×1
list ×1
optional ×1