如果您使用Eclipse Collections,您可以编写以下代码。首先,我们设置您指定的范围:
private ImmutableList<Interval> ranges = Lists.immutable.with(
Interval.fromTo(0, 29),
Interval.fromTo(30, 39),
Interval.fromTo(40, 69),
Interval.fromTo(70, 100));
然后我们可以在示例中使用这些范围,使用匿名内部类。
final MutableBag<Interval> countByRange = Bags.mutable.empty();
Interval inputs = Interval.from(5).to(100).by(5);
inputs.forEach(new IntProcedure()
{
public void value(final int grade)
{
countByRange.add(ranges.detect(new Predicate<Interval>()
{
public boolean accept(Interval range)
{
return range.contains(grade);
}
}));
}
});
countByRange.forEachWithOccurrences(new ObjectIntProcedure<Interval>()
{
public void value(Interval range, int occurrences)
{
System.out.println(range + " : " + StringIterate.repeat('*', occurrences));
}
});
您需要将 Interval 输入替换为您的实际输入(在您的示例中为 Scanner)。我只想要一组简单的输入来测试。
代码的输出如下:
Interval from: 70 to: 100 step: 1 size: 31 : *******
Interval from: 40 to: 69 step: 1 size: 30 : ******
Interval from: 30 to: 39 step: 1 size: 10 : **
Interval from: 0 to: 29 step: 1 size: 30 : *****
使用 Java 8 Lambda 语法,您可以编写以下内容:
MutableBag<Interval> countByRange = Bags.mutable.empty();
Interval inputs = Interval.from(5).to(100).by(5);
inputs.forEach((int grade) -> {
countByRange.add(ranges.detect(range -> range.contains(grade)));
});
countByRange.forEachWithOccurrences((range, occurrences) ->
{System.out.println(range + " : " + StringIterate.repeat('*', occurrences));});
如果您想尝试使用 collect 而不是使用 forEach 添加到包中,以下代码会产生相同的结果。
Interval.from(5).to(100).by(5)
.collect(grade -> ranges.detect(range -> range.contains(grade)))
.toBag()
.forEachWithOccurrences((range, occurrences) ->
{System.out.println(range + " : " + StringIterate.repeat('*', occurrences));});
注意:我是 Eclipse 集合的提交者。