java-更好的lambda以获得对象层次结构上的不同值
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java-更好的lambda以获得对象层次结构上的不同值,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2516字,纯文字阅读大概需要4分钟。
内容图文
![java-更好的lambda以获得对象层次结构上的不同值](/upload/InfoBanner/zyjiaocheng/684/2a3fd7cb0336483a9a694b19a4ebced6.jpg)
我们有一个对象A类型,它包含一个对象B类型的数组,而不是包含一个对象C类型的数组,如示例中所示:
/* sample structure that ends with 4 instances of C with ids.100,200,100,200 */
private class A{
int id;
A(int id) {
this.id = id;
}
B[] b = new B[]{new B(10), new B(20) };
}
private class B{
int id;
B(int id) {
this.id = id;
}
C[] c = new C[]{new C(100), new C(200) };
}
private class C{
int id;
C(int id) {
this.id = id;
}
public String toString(){
return ""+id;
}
}
如果我们尝试获取所有不同的c.id(100,200),则第一种方法可能是
HashSet<Integer> distinctIdsOfC = new HashSet<Integer>();
for (B bbb: a.b){
for (C ccc: bbb.c){
distinctIdsOfC.add(ccc.id);
}
}
(结果是100,200预期的)
和我的第一个lambdas attepmt
List<C> a6 = Arrays.asList(a.b).stream().map(jaja -> Arrays.asList(jaja.c)).flatMap(List::stream).collect(Collectors.toList());
a6.stream().map(x->x.id).distinct().forEach(System.out::println);
(结果仍然是预期的100、200)
最后是问题.有更好的替代lambda吗?
/* Complete source sample to test */
package test;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;
public class Test {
public static void main(String[] args) {
Test t = new Test();
t.haz();
}
private void haz() {
A a = new A(1);
HashSet<Integer> distinctIdsOfC = new HashSet<Integer>();
for (B bbb : a.b) {
for (C ccc : bbb.c) {
distinctIdsOfC.add(ccc.id);
}
}
System.out.println("with for-loop" + distinctIdsOfC.toString());
System.out.println("with lambda");
List<C> a6 = Arrays.asList(a.b).stream().map(jaja -> Arrays.asList(jaja.c)).flatMap(List::stream)
.collect(Collectors.toList());
a6.stream().map(x -> x.id).distinct().forEach(System.out::println);
}
private class A {
int id;
A(int id) {
this.id = id;
}
B[] b = new B[] { new B(10), new B(20) };
}
private class B {
int id;
B(int id) {
this.id = id;
}
C[] c = new C[] { new C(100), new C(200) };
}
private class C {
int id;
C(int id) {
this.id = id;
}
public String toString() {
return "" + id;
}
}
}
解决方法:
好的,我认为我们有很多选择,但:
1)在C类中实现equlas / hashCode,然后:
Arrays.stream(a.b)
.map(s -> s.c)
.flatMap(Arrays::stream)
.distinct()
.forEach(System.out::println)
但是,如果您不能添加hashCode / equals:
2)创建过滤方法(按类区分):
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Map<Object,Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
然后像这样写lambda:
Arrays.asList(a.b).stream()
.map(jaja -> Arrays.asList(jaja.c))
.flatMap(List::stream)
.filter(distinctByKey(s -> s.id))
.forEach(System.out::println);
内容总结
以上是互联网集市为您收集整理的java-更好的lambda以获得对象层次结构上的不同值全部内容,希望文章能够帮你解决java-更好的lambda以获得对象层次结构上的不同值所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。