【发布时间】:2019-01-14 12:05:18
【问题描述】:
对于一个项目,我想检查 String 是否与我的一个对象中的 String 属性相同。
例如,我有 3 个项目对象:
Item spotion = new Item("small potion", 5, 0, 0, 0, 0, 0);
Item mpotion = new Item("medium potion", 20, 0, 0, 0, 0, 0);
Item lpotion = new Item("large potion", 35, 0, 0, 0, 0, 0);
然后我想检查一下
String s = spotion;
将等于Item 的任何名称(第一个属性);
是否有任何方法可以做到这一点,而不创建要循环通过的项目的ArrayList,而是只查看有多少项目并在创建时循环?
【问题讨论】:
-
您需要
Item类中的公共字段或getter 才能获得第一个属性。 -
item.name.equals("some string") -
我已经有一个 getter 问题是我不知道如何为 Items 设置一个循环,而不必创建一个可以循环的 ArrayList。
-
您可以使用流:
long count = Stream.of(spotion, mpotion, lpotion).filter(item -> item.name.equals(s)).count()