我对 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) 鉴于:
List<String> myStrings = Arrays.asList("broom", "monsoon");
Run Code Online (Sandbox Code Playgroud)
返回:
Map<String, Long> stringToNumberOfVowels = Map.of("broom", 2, "monsoon", 3);
Run Code Online (Sandbox Code Playgroud)
这是我尝试过的:
Map<String, Long> vowelsMap = Stream.of("broom").flatMapToInt(String::chars).filter("aeiou".indexOf(c) >= 0).mapToObj(c -> "aeiou".indexOf(c)>=0 ? "broom" : "").collect(Collectors.groupingBy(Function.indenty(), Collectors.counting()));
for(Map.Entry<String, Long> a : vowelsMap.entrySet()) { System.out.println(a.getKey() + "==>"); System.out.println(a.getValue()); }
Run Code Online (Sandbox Code Playgroud)
我的输出(仅适用于流中传递的 1 个字符串):
扫帚==> 2
期望的输出:
扫帚==> 2
季风==> 3
我有一群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)
我正在使用一套收集器。
为什么这段代码不能为我编译?
我尝试使用stream和toMap选项将List转换为Map
List<CountryToPaymentMethodsDisplayRules>
paymentMethodDisplayRulesByCountryList =
gatway.getCountryPaymentMethodsDisplayRulesByCountry();
Map<PaymentMethod, CountryToPaymentMethodsDisplayRules>
countryToPaymentMethodsDisplayRulesMap = paymentMethodDisplayRulesByCountryList
.stream()
.collect(Collectors.toMap(type -> type.getCountryToPaymentMethodsDisplayRules().getPaymentMethod(),
type -> type));
public interface PaymentMethod extends Serializable {
}
public enum PaymentMethodType implements PaymentMethod, Serializable {
}
public interface CountryToPaymentMethodsDisplayRules {
public PaymentMethod getPaymentMethod();
}
public class CountryToPaymentMethodsDisplayRulesEntity implements CountryToPaymentMethodsDisplayRules, PersistentEntity<Long>, Serializable {
@Type(type = "com.plimus.core.payment.PaymentMethodTypeUserType")
@Column(name = "PAYMENT_TYPE")
private PaymentMethod paymentMethod;
}
Run Code Online (Sandbox Code Playgroud)
这有什么不对?
我想按键对地图对象进行分组。我尝试使用此代码,但出现编译错误:
Non-static method cannot be referenced from a static context
Run Code Online (Sandbox Code Playgroud)
我的代码:
Map<String, List<A>> getAMap() {
return Arrays.stream(SomeArray.values())
.map(map -> createObject())
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
}
private Map<String, A> createObject()
final A a = new A(some attributes);
Map<String, A> map = new LinkedHashMap<>();
map.put(some key, a);
.... // add another values.
return map;
}
Run Code Online (Sandbox Code Playgroud)
我需要类似的东西
{
"a", {a1, a2, a3},
"b", {a4, a5, a6},
}
Run Code Online (Sandbox Code Playgroud) 相对较新到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) int val = integerList.stream().collect(
Collectors.reducing(0, a1 -> a1 * 5, (a1, a2) -> a1 + a2));
Run Code Online (Sandbox Code Playgroud)
上面的代码进行了归约操作。转换整数流和聚合函数以返回 Integer 。我无法理解以下代码和归约操作的内部实现。Java 如何执行以下有状态功能?谢谢!
java.util.stream.Collectors:reducing method
public static <T, U>
Collector<T, ?, U> reducing(U identity,
Function<? super T, ? extends U> mapper,
BinaryOperator<U> op) {
return new CollectorImpl<>(
boxSupplier(identity),
(a, t) -> { a[0] = op.apply(a[0], mapper.apply(t)); },
(a, b) -> { a[0] = op.apply(a[0], b[0]); return a; },
a -> a[0], CH_NOID);
}
Run Code Online (Sandbox Code Playgroud)
可能是,我会更好地澄清我的问题。上面的实现是如何获取数据流的。a[0],b[0] 是指数据流吗?我相信以上是为供应商和累加器提供功能实现。我想通过代码了解缩减过程是如何工作的。
collectors ×7
java ×7
java-8 ×4
java-stream ×4
lambda ×3
dictionary ×2
arraylist ×1
collections ×1
grouping ×1
hashmap ×1
reducing ×1