关于java语言表达力不足的几个例子及可有好的封装方法
巴扎黑
巴扎黑 2017-04-18 09:56:58
0
9
453

开发业务过程中 明显感觉到java语言表达力的不足 就好像没有桌子的概念 所以每次提到桌子都得通过这么一长串的文字--有光滑平板、由腿或其它支撑物固定起来的家具,用以吃饭、写字、工作或玩牌--来表达桌子的概念 反正开发过程中我是有点晕

下面是几个比较典型的例子

业务背景

  • 购买某些商品 会给用户发一些优惠券 如2张满100减50优惠券 1张满200减50优惠券等

  • 我提供一个了接口 接收上述券信息

  • 先查询redis判断该券是不是已经存在 如hmget key 100_50 200_50

  • 如果券不存在 先去创建 然后将其放到redis中 如hmset key 100_50 84678bfd7c1011e6a22b4437e6d0648e

  • 最后得到券编码和张数的映射关系 批量发券batchSendCouponsToUser(userId,couponCodeCountMap);

两个元素集合 找出对应的另一个集合中同一位置为空的元素

String[] descArray = {"aaa", "bbb", "ccc"}; // 券描述 如 满100减50 List codeList = newArrayList("111", null, "333"); // 券编码 // 找出尚不存在code的券 List nullElementList = newArrayList(); for (int i = 0; i < codeList.size(); i++) { if (codeList.get(i) == null) { nullElementList.add(descArray[i]); } } assertThat(nullElementList).containsExactly("bbb");

一个集合与一个Map通过另一个集合来关联 并生成一个新的Map

String[] descArray = {"aaa", "bbb", "ccc"}; // 券描述 List codeList = newArrayList("111", "222", "333"); // 券编码 Map descCouponInfoMap = ImmutableMap.of("aaa", new CouponInfo("aaa", 1), "bbb", new CouponInfo("bbb", 2), "ccc", new CouponInfo("ccc", 3)); // 券描述 -- 券信息 // 得到券编码与发放张数Map Map 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));

两个对象list各抽取一个属性 组成一个Map

List fooList = newArrayList(new Foo("aaa"), new Foo("bbb"), new Foo("ccc")); List barList = newArrayList(new Bar("111"), new Bar("222"), new Bar("333")); Map descCodeMap = new HashMap<>(); // 券描述 -- 券编码 // 将两个List各抽取一个属性成Map 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"));

像第一个还好, 可以提供一个通用的工具类如

static List findNullElementList(List srcList, List destList)

后面两个因为涉及到动态的获取属性值 还不好封装 难道使用java就只能这么麻烦吗?

不知道其他语言针对上述场景是不是一样的麻烦?
如 python javascript ruby 等

巴扎黑
巴扎黑

reply all (9)
左手右手慢动作

I don’t quite understand what you meant by your first paragraph...

My understanding is: Is there any convenient tool that can achieve your needs?

Yes, the most indispensable thing about Java is tools. Basically, as long as you think of the tools you need, search online, and you can find them in 99% of the cases.

It is recommended to usejava8+google guava, it can be used in any combination, it is better to use both at the same time.

Based on the situations you mentioned in these 3 examples, here are the answers one by one:

Q: Two element sets. Find the empty element at the same position in the corresponding other set
A: First, it is recommended to write a zip method to mergedescArraycodeListinto an object array, and then operate on the object array.

public static  List> zip(List list1, List list2) throws IllegalArgumentException { if (list1 == null || list2 == null || list1.size() != list2.size()) { throw new IllegalArgumentException("Two list must have the same size"); } List> results = Lists.newArrayListWithCapacity(list1.size()); for (int i = 0; i < list1.size(); ++i) { // Explicit type parameter just because eclipse is not cool // noinspection RedundantTypeArguments Pair pair = Pair.of(list1.get(i), list2.get(i)); results.add(pair); } return results; }

Then:

List> empytCodeList = zip(codeList, descList).stream() .filter(v -> Objects.isNull(v.getFirst()))// 找出codeList中为空的对象 .collect(Collectors.toList());

Q: A set is associated with a Map through another set and generates a new Map

A: In the same way, first zip the two arrays into object arrays, then:

Map codeCountMap = zip(codeList, descList).stream() .collect(Collectors.toMap(Pair::getFirst, v -> descCouponInfoMap.get(v.getSecond()).getCount()));//这里有个隐患就是map.get(desc)有可能未null,从而引发空指针

Q: Each of the two object lists extracts an attribute to form a Map

A: In the same way, first zip the two arrays into object arrays, then:

Map descCodeMap = zip(fooList, barList).stream() .collect(Collectors.toMap(v -> v.getFirst().getDesc(), v -> v.getSecond().getCode()));

You mentioned dynamically obtaining attribute values. Before java8, you could dynamically obtain attribute values through reflection. In java8, you could obtain them through method references. Here I take java8 as an example:

public static void getFieldVal(Supplier supplier) { return supplier.get(); }

couponInfo::getCount就是一个supplier, based on this principle, many functions that could only be realized through reflection in the past can be realized in java8 throughmethod reference.

The above, even if you don’t use Java8, you can use guava to elegantly implement these functions.

Reference:

  1. http://ifeve.com/google-guava/

  2. http://www.importnew.com/1036...

  3. http://www.importnew.com/1190...

    大家讲道理

    In fact, Java 8 does not require zip,

    import java.util.*; import java.util.stream.*;

    Find the corresponding collection that is empty

    List result = IntStream.range(0, descArray.length) .filter(i -> codeList.get(i) == null) .mapToObj(i -> descArray[i]) .collect(Collectors.toList());

    Related Map

    Map codeCountMap = IntStream.range(0, descArray.length) .boxed() .collect(Collectors.toMap( i -> codeList.get(i), i -> descCouponInfoMap.get(descArray[i]).getCount()));

    Generate Map

    Map descCodeMap = IntStream.range(0, descArray.length) .boxed() .collect(Collectors.toMap( i -> descArray[i], i -> codeList.get(i)));
      大家讲道理

      Obviously this is your problem.
      Do you know what classes and objects are?
      Using list map for everything is of course not possible.
      You define a coupon class with code and desc attributes
      List ticketList;
      for(Ticket ticket:ticketList){
      if(ticket.getCode()==null){

      System.out.println(ticket.getDesc());

      }
      }

      I won’t mention the second and third ones.

        小葫芦

        The shortcomings of high-rise design cannot be made up for by the bottom floor.

          阿神

          The poster needs to strengthen abstract design and data structure design.
          The first scene is a very unstable design based on position. There should be a specific type

          class Coupon { int id; //对应位置,保证不重复,也不会错位。 String desc; String code; public boolean notUsed() { return code == null; } }

          It will be easier to find the ones with empty code in the List, but even better, use an unusedList to save all notUsedCoupon.

          The second scenario is used as classification statistics. There is a ready-made grouping method in guava. After the grouping is constructed, the number of each group will be known.

          In the third scenario, it is not necessary to take an attribute each. In fact, you can construct an object reference to Foo and Bar, and use delegation to
          these two objects respectively.

          As the respondent mentioned above, there is a lack of high-level design here. When there are three attributes a, b, and c, if you design three Lists respectively, then there will be a search process of
          a->b, b->c, and a more complicated operation is a->( b, c). If they are in an object, then a->o(a,b,c) can complete most of the data indexing work.

            Peter_Zhu

            Python is an interpreted language that can dynamically obtain attributes at runtime

            I don’t know Java very well, but there should be several similar reflection mechanisms.

              左手右手慢动作

              Java is an ancient language. If it is not expressive enough as you said, why has it become the most popular language in the world? It’s just that you didn’t learn it well

                Ty80

                Don’t use arrays or lists to separate tickets and codes. There should be a one-to-one relationship between tickets and codes. When building a model, you can create a ticket class with a code attribute in it. Isn’t this very clear?

                  洪涛

                  Java is a verbose language, and the codes written in java are basically quite verbose (before 8).
                  Java alone is not as elegant as pyhton and other languages in handling basic operations, but it can be compensated for by tool classes and other Groovy.

                    Latest Downloads
                    More>
                    Web Effects
                    Website Source Code
                    Website Materials
                    Front End Template
                    About us Disclaimer Sitemap
                    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!