Java按属性筛选模型列表并返回筛选列表
我有一张模型班的名单。它包含两个字段:Java按属性筛选模型列表并返回筛选列表,java,arraylist,lambda,hashmap,set,Java,Arraylist,Lambda,Hashmap,Set,我有一张模型班的名单。它包含两个字段: Class Model { String id; String type; } 我有一个地图结构: Map每个字符串表示映射到列表的名称 现在我想检查名称是否有一个独特的列表。只有当每个模型具有不同的类型时,该列表才会考虑不同。如果有模式A(“abc”,“绿色”),接下来如果我看到模式B(“dbc”,“绿色”),模式C(“drrt”,“绿色”),那么模式B,模式C没有区别,我想存储名称和模式B,模式C,并返回映射,它表示与非区分的列表一起
Class Model {
String id;
String type;
}
我有一个地图结构:
Map
每个字符串表示映射到列表的名称
现在我想检查名称是否有一个独特的列表
。只有当每个模型具有不同的类型时,该列表才会考虑不同。如果有模式A(“abc”,“绿色”)
,接下来如果我看到模式B(“dbc”,“绿色”)
,模式C(“drrt”,“绿色”)
,那么模式B,模式C
没有区别,我想存储名称
和模式B,模式C
,并返回映射
,它表示与非区分的列表
一起使用的名称
我想建立一个映射
结构,类型
作为键,一个集合
作为值,当我迭代列表
时,我检查映射
是否包含我看到的键,如果是,将id
添加到集合
,如果添加成功,意味着它是不独特的,我将把它们添加到结果映射中
但是,是否有其他方法,或者更优雅/简单/高效的方法,使用Java库或Lambda等?请帮忙~~~怎么样
public class Main {
public static void main(String[] args) {
Map<String, List<Model>> map = Stream.of(
new Model("1", "type1"),
new Model("2", "type2"),
new Model("3", "type2")
)
.collect(groupingBy(m -> "name"));
Map<String, List<Model>> dupes = map.entrySet().stream()
.flatMap(e -> e.getValue().stream()
.collect(groupingBy(Model::getType))
.entrySet().stream()
.filter(e1 -> e1.getValue().size() > 1)
.map(e1 -> new SimpleImmutableEntry<>(e.getKey(), e1.getValue())))
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
System.out.println(dupes);
}
private static class Model {
private final String id;
private final String type;
public Model(String id, String type) {
this.id = id;
this.type = type;
}
public String getId() {
return id;
}
public String getType() {
return type;
}
@Override
public String toString() {
return "Model{" +
"id='" + id + '\'' +
", type='" + type + '\'' +
'}';
}
}
}
公共类主{
公共静态void main(字符串[]args){
Map=Stream.of(
新型号(“1”、“1型”),
新型号(“2”、“类型2”),
新型号(“3型”、“2型”)
)
.收集(分组方式(m->“名称”);
Map dupes=Map.entrySet().stream()
.flatMap(e->e.getValue().stream())
.collect(groupingBy(Model::getType))
.entrySet().stream()
.filter(e1->e1.getValue().size()>1)
.map(e1->new simpleimutableentry(e.getKey(),e1.getValue()))
.collect(toMap(Map.Entry::getKey,Map.Entry::getValue));
系统输出打印项次(重复);
}
私有静态类模型{
私有最终字符串id;
私有最终字符串类型;
公共模型(字符串id、字符串类型){
this.id=id;
this.type=type;
}
公共字符串getId(){
返回id;
}
公共字符串getType(){
返回类型;
}
@凌驾
公共字符串toString(){
返回“Model{”+
“id=”+id+“\”+
,type=''+type+'\''+
'}';
}
}
}
打印{name=[Model{id='2',type='type2'},Model{id='3',type='type2'}]}您的问题非常令人困惑。尽量简化和澄清你的意思。也许可以用代码以外的东西来解释你的问题。你所寻找的一点都不难,但到目前为止你尝试了什么?自己编写一些代码,遇到问题时再回来。我们不会为你写代码的。