我有一个类Class1
有3个属性(prop1
,prop2
,prop3
)。我有一个带有Hashmap hashMap1的Class Class2。我在hashMap1中使用Class1对象并为prop1
,prop2
,prop3
插入一个值。
1类
public class Class1
{
private String Prop1;
private String Prop2;
private int Prop3;
public Class1(String Prop1, String Prop2, int Prop3)
{
this.Prop1= Prop1;
this.Prop2= Prop2;
this.Prop3= Prop3;
}
}
等级2
public class Class2
{
public static void main(String[] args)
{
HashMap<String, Class1> hashMap1= new LinkedHashMap<>();
hashMap1.put("01" , new Class1("Prop1a","Prop2a", 101));
hashMap1.put("02" , new Class1("Prop1a","Prop2b", 202));
hashMap1.put("03" , new Class1("Prop1b","Prop2a", 303));
}
}
我想知道,我如何打印来自集合的所有列表Prop1 = "Prop1a"
或Prop2 = "Prop2a"
?我希望有道理。
如果有更好的方法可以实现,请告诉我。
旧学校(简单,适用于所有版本的Java)使用循环。
public static void main(String[] args)
{
HashMap<String, Class1> hashMap1= new LinkedHashMap<String, Class1>();
hashMap1.put("01" , new Class1("Prop1a","Prop2a", 101));
hashMap1.put("02" , new Class1("Prop1a","Prop2b", 202));
hashMap1.put("03" , new Class1("Prop1b","Prop2a", 303));
for( Class1 c : hashMap1.values() ) {
if( c.getProp1().equals( "Prop1a" ) || c.getProp2().equals( "Prop2a" ) )
System.out.println( c );
}
}
请注意,你当然需要Class1
中的getter,并且被覆盖的toString
很有用。
class Class1
{
private String Prop1;
private String Prop2;
private int Prop3;
public String getProp1() {
return Prop1;
}
public String getProp2() {
return Prop2;
}
public int getProp3() {
return Prop3;
}
public Class1(String Prop1, String Prop2, int Prop3)
{
this.Prop1= Prop1;
this.Prop2= Prop2;
this.Prop3= Prop3;
}
@Override
public String toString() {
return "Class1{" + "Prop1=" + Prop1 + ", Prop2=" + Prop2 + ", Prop3=" + Prop3 + '}';
}
}
如果你想获得具有特定属性的Class1
列表,也可以通过stream api来完成:
Predicate<Class1> prop1Predicate = class1 -> class1.getProp1().equals("Prop1a");
Predicate<Class1> prop2Predicate = class1 -> class1.getProp2().equals("Prop2a");
List<Class1> list = hashMap1.values().stream()
.filter(prop1Predicate.or(prop2Predicate))
.collect(Collectors.toList()); // or .forEach(System.out::println); to print (without return value)
您需要在Class1中创建getter,理想情况下还要覆盖toString()方法以您想要的方式打印Class1。然后你可以做这样的事情:
for (Map.Entry<String, Class1> entry : hashMap1.entrySet()) {
Class1 value = entry.getValue();
if (value.getProp1().equals("Prop1a") || value.getProp2().equals("Prop2a")) {
System.out.println(value);
}
}
我没有测试代码,如果它不起作用,请在评论中告诉我。
您需要迭代地图的值,选择符合条件的值并打印它们。一种方法是使用流:
hashMap1.entrySet()
.stream()
.filter(c1 -> c1.getProp1().equals("Prop1a") || c1.getProp2.equals("Prop2a"))
.forEach(c1 -> System.out.println(c1));
你需要为toString()
实现基本的getter和Class1
。