java - 在 HashSet 中传递方法是个好习惯吗?

标签 java methods set hashset

在 HashSet 中传递方法是否是一个好习惯,如下所示,我直接在 HashSet 中传递方法?

Set byPrice = new HashSet(getProductsByPriceFilter( lowPrice, highPrice));**

  public Set<Product> filterProducts(BigDecimal lowPrice,
                BigDecimal highPrice, String manufacturer, String category) {

            Set<Product> byPrice = new HashSet<Product>(getProductsByPriceFilter(
                    lowPrice, highPrice));
            Set<Product> byManufacturer = new HashSet<Product>(
                    getProductsByManufacturer(manufacturer));
            Set<Product> byCategory = new HashSet<Product>(
                    getProductsByCategory(category));

            byPrice.retainAll(byManufacturer);
            byPrice.retainAll(byCategory);

            return byPrice;
        }

最佳答案

对此的一个想法:如果您的方法已经返回可以填充整个 Set 的内容 - 为什么不让方法返回该 Set?

Set<Product> byPrice = getProductsByPriceFilter(
                lowPrice, highPrice));

有一些

public Set <Product> getProductsByPriceFilter(double low, double high) {

其他过滤器也是如此。

或者...将已经过滤的集合传递到下一阶段。您可能在 getProductsByManufacturer () 中对所有产品进行了循环。如果您添加已过滤的集合作为参数,您可以减少此循环以循环遍历已在价格范围内的所有产品等。

关于java - 在 HashSet 中传递方法是个好习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34781854/

相关文章:

java - 抛硬币方法建议

c# - 使用 Moq 验证使用不同状态的对象的方法调用

java - 创建的类和公共(public)方法未转到测试方法

python - 如何迭代生成集合中所有可能的元素组合

java - 再一次 => "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server... "

java - 如何保持结果集打开,或调用不同的结果集?

java - 在java中创建主类的静态单例是不好的编程习惯吗?

java - 如何使用一个Bootstrap连接Netty中的多个服务器

algorithm - 分析不同的集合和优化。最好的方法?

python - 对大型 Python 集的操作