我有以下课程:
public final class InfoWrapper {
private int count;
private int itemCode;
private String name;
public InfoWrapper() {
}
public InfoWrapper(final int count, final int itemCode, final String name) {
super();
this.count = count;
this.itemCode = itemCode;
this.name = name;
}
public int getCount() {
return count;
}
public int getItemCode() {
return itemCode;
}
public String getName() {
return name;
}
}
这是我的测试课:
public class TestClass {
public static void main(String [] args) {
Deque<InfoWrapper> list = new ArrayDeque<InfoWrapper>();
list.add(new InfoWrapper(3, 111, "aaa"));
list.add(new InfoWrapper(7, 112, "bbb"));
list.add(new InfoWrapper(12, 113, "ccc"));
list.add(new InfoWrapper(6, 113, "ccc"));
list.add(new InfoWrapper(8, 113, "ccc"));
list.add(new InfoWrapper(3, 113, "ccc"));
System.out.println("Is good enought : " + isGoodEnought(list, 3));
}
private static boolean isGoodEnought(final Deque<InfoWrapper> list, final int maxFailsCount) {
return !list.stream().limit(maxFailsCount).skip(1).anyMatch((res) -> res.getName().equals("ccc"));
}
}
我的方法是GoodEnough()检查在前3个元素中名称不等于“ccc”,但实际上我需要检查名称是否唯一。
答案 0 :(得分:4)
private static boolean isGoodEnought(Deque<InfoWrapper> list,
int maxFailsCount) {
return list.stream()
.limit(maxFailsCount)
.map(InfoWrapper::getName)
.distinct()
.count() == maxFailsCount;
}
请注意,即使前两个名称相等,这也会遍历maxFailsCount
个元素。如果maxFailsCount
可能是一个很大的值,您可能希望使用类似
private static boolean isGoodEnought(Deque<InfoWrapper> list, int max) {
Set<String> seenNames = new HashSet<>();
for (Iterator<InfoWrapper> i = list.iterator(); i.hasNext() && max-- > 0;)
if (!seenNames.add(i.next().getName()))
return false;
return true;
}