在日常开发中,我发现有些场景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/