java - 如何为这些场景包装 util 方法

标签 java

在日常开发中,我发现有些场景java确实很不方便,例如

示例1

    String[] descArray = {"aaa", "bbb", "ccc"};  // coupon desciption
    List<String> codeList = newArrayList("111", null, "333"); // coupon code
    // find those coupon which does not have code
    List<String> nullElementList = newArrayList();
    for (int i = 0; i < codeList.size(); i++) {
        if (codeList.get(i) == null) {
            nullElementList.add(descArray[i]);
        }
    }
    assertThat(nullElementList).containsExactly("bbb");

示例2

    String[] descArray = {"aaa", "bbb", "ccc"}; // coupon description
    List<String> codeList = newArrayList("111", "222", "333"); // coupon code
    Map<String,CouponInfo> descCouponInfoMap = ImmutableMap.of("aaa", new CouponInfo("aaa", 1), "bbb", new CouponInfo("bbb", 2), "ccc", new CouponInfo("ccc", 3)); // desc -- couponInfo

    // to generate new Map<code, count>
    Map<String,Integer> codeCountMap = new HashMap<>();
    for (int i = 0; i < codeList.size(); i++) {
        codeCountMap.put(codeList.get(i), descCouponInfoMap.get(descArray[i]).getCount());
    }


    assertThat(codeCountMap).containsExactly(new DefaultMapEntry("111",1),new DefaultMapEntry("222",2),new DefaultMapEntry("333",3));

示例3

    List<Foo> fooList = newArrayList(new Foo("aaa"), new Foo("bbb"), new Foo("ccc"));
    List<Bar> barList = newArrayList(new Bar("111"), new Bar("222"), new Bar("333"));
    Map<String,String> descCodeMap = new HashMap<>();

    for (int i = 0; i < fooList.size(); i++) {
        descCodeMap.put(fooList.get(i).getDesc(), barList.get(i).getCode());
    }

    assertThat(descCodeMap).contains(new DefaultMapEntry("aaa","111"),new DefaultMapEntry("bbb","222"),new DefaultMapEntry("ccc","333"));

如示例 1 所示,可以提供下面包装的 util 方法来实现它

static <T>List<T> findNullElementList(List<T> srcList, List<T> destList)

但是最后两个怎么样?开发者可以动态指定对象的某些属性。

最佳答案

看看您给出的示例,我怀疑您会发现它不方便,因为您没有真正发挥 OO 设计的全部潜力。

以下面为例:

String[] descArray = {"aaa", "bbb", "ccc"};  // coupon desciption
List<String> codeList = newArrayList("111", null, "333"); // coupon code

您将 3 个对象的属性存储在 2 个单独的数组中。如果您只有一个 Coupon 类,您可以开始封装该对象的一些行为并导致更好的设计:

for(Coupon coupon : coupons) {
    if(coupon.getDescription() == null) {
        nullElementList.add(coupon);
    }
}

关于java - 如何为这些场景包装 util 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39315952/

相关文章:

java - 特别是Http outbound-gateway : is there a way to handle not HTTP errors and,、 "no connection"错误?

java - MySQL 查询使用公共(public)字符串方法返回字符串

java - JOOQ:一次性删除记录列表?

java - 泽西 Restful 异常(exception) 1

java - 有效地将三个字母的货币名称转换为符号名称(例如 20 美元到 20 美元)

java - 导致空字段的 Jena TDB 插入语句

java - 使用 Jackson 反序列化时如何放宽命名策略?

java - 如何使用designgridlayout在页面中的两类数据之间插入垂直JSeperator?

java - 如果未明确提交或回滚,则自动提交事务

java - 如何根据两列的范围查询HBase?