【问题标题】:Print out the strings that are >= a threshold using a foreach loop?使用foreach循环打印出> =阈值的字符串?
【发布时间】:2016-11-04 17:59:56
【问题描述】:
public Set<String> filterAlleles (int threshold) {
    Set<String> filtered = new HashSet<String>();
    Map<String, Integer> counted = this.countAlleles();
    for (String allele : _alleles){

我之前编写了 countAlleles 方法,所以我按照说明在此方法声明中使用它。 countAlleles 方法返回等位基因和它发生的次数。

【问题讨论】:

  • 这也应该用编程语言名称标记。
  • 迭代counted映射并删除值小于阈值的条目(在#entrySet上使用Iterator),然后打印映射

标签: java string foreach filter


【解决方案1】:

这是一个使用 for 循环的示例代码,它将过滤 >= 7 的数据并打印它们。由于您提供的代码很少,我将附上示例,希望对您有所帮助。

public static void main(String[] args) {
    Map<String,Integer> counted = new HashMap<>();
    counted.put("foo", 3);
    counted.put("bar", 10);
    counted.put("baz", 6);
    counted.put("goo", 11);

    counted.entrySet().stream()                // Stream the entry set
            .filter(e->e.getValue() >= 7)      // Filter on >= threshold
            .map(Map.Entry::getKey)            // Get the key since it's the name we are looking for
            .forEach(System.out::println);     // Print the list
}

【讨论】:

  • 把它收集到一个列表有什么意义?在这种情况下,这就像一个无操作。
  • 如果他们想对字符串进行进一步操作,否则可以省略收集。这是一个例子,因为这个问题提供的信息太少了。
猜你喜欢
  • 2016-11-05
  • 2014-08-20
  • 1970-01-01
  • 1970-01-01
  • 2012-07-07
  • 1970-01-01
  • 2014-02-17
  • 2015-02-13
  • 1970-01-01
相关资源
最近更新 更多