DWQA QuestionsCategory: ProgramSeveral examples of Java language's inadequate expressiveness and good encapsulation methods
zhuguowei2 asked 3 years ago

In the process of developing business, it is obvious that the lack of expressiveness of Java language is like the concept of no desk, so every time a desk is mentioned, it has to pass through such a long string of words.Furniture with a smooth flat surface fixed by legs or other supports for eating, writing, working, or playing cards.To express the concept of a table, I was a little dizzy in the development process anyway.
Here are some typical examples
Business background

  • Buying certain goods will give users some coupons, such as 2 coupons of 100% less 50% and 1 coupon of 200% less 50, etc.
  • I provided an interface to receive the above coupon information.
  • Query redis first to see if the ticket already exists.hmget key 100_50 200_50
  • If the ticket does not exist, create it first and then place it in redis such as hmset key 100_50 84678 bfd7c1011e6a22b4437 e6d0648e
  • Finally, the mapping relationship between the number of tickets and the number of tickets is obtained.batchSendCouponsToUser(userId,couponCodeCountMap);

Two sets of elements find the same empty element in the corresponding set

String [] descArray = {aaa,""bbb,""ccc"}; // Voucher description as full as 100 minus 50
        List < String > codeList = new ArrayList ("111", "null", "333"); // Voucher Coding
        // Find tickets that do not yet have code
        List<String> nullElementList = newArrayList();
        for (int i = 0; i < codeList.size(); i++) {
            if (codeList.get(i) == null) {

A collection is associated with a Map through another collection and generates a new Map

String [] descArray = {aaa,""bbb,""ccc"}; // Voucher Description
        List < String > codeList = new ArrayList ("111", "222", "333"); // Voucher Coding
        Map < String, CouponInfo > descCouponInfoMap = ImmutableMap. of ("aaa", "new CouponInfo" ("aaa", 1), "bbb", "new CouponInfo" ("bbb", 2), "ccc", "new CouponInfo" ("ccc", 3); //coupon description - coupon information
        // Get ticket code and issue ticket number Map
        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));

Two object lists each extract an attribute to form a Map

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 <>(); // Voucher Description - Voucher Coding
        // Extract one attribute from each of the two Lists into 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"));

As good as the first one, you can provide a generic tool class such as

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

The latter two are not well encapsulated because they involve dynamic acquisition of attribute values. Can it only be so troublesome to use java?
I wonder if other languages have the same trouble with the above scenarios?
For example, Python JavaScript ruby, etc.

9 Answers
Best Answer
GoldyMark answered 3 years ago

I don’t quite understand the meaning of your first paragraph…
I understand: Is there a convenient tool to meet your needs?
Yes, the most indispensable part of Java is the tool class. Basically, as long as you think of what tools you need, you can search on the Internet, and 99% of the cases can be found.
Suggested usejava8+google guavaIt can be used in any combination, and it is better to use both at the same time.
In the case of your three examples, the answers are as follows:

Q: Two sets of elements find the same empty element in the corresponding set
A: First of all, it is suggested to write a zip method.descArrayandcodeListMerge into an array of objects, and then operate on the array of objects.

public static <U, V> List<Pair<U, V>> zip(List<? extends U> list1, List<? extends V> list2) throws IllegalArgumentException {
    if (list1 == null || list2 == null || list1.size() != list2.size()) {
        throw new IllegalArgumentException("Two list must have the same size");
    List<Pair<U, V>> 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<U, V> pair = Pair.<U, V>of(list1.get(i), list2.get(i));
    return results;


List<Pair<String, String>> empytCodeList = zip(codeList, descList).stream()
    Filter (v - > Objects. isNull (v. getFirst ())/// Find empty objects in codeList

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

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

Map<String, Integer> codeCountMap = zip(codeList, descList).stream()
                Collectors. toMap (Pair:: getFirst, v-> descCouponInfoMap. get (v. getSecond (). getCount (); /// There is a hidden danger that map. get (desc) may not have null, thus triggering a null pointer.

Q: Two object lists each extract an attribute to form a Map

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

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

The dynamic acquisition of attribute values mentioned by you can get attribute values dynamically by reflection before Java 8. In Java 8, you can get attribute values by method reference. Here I take Java 8 as an example:

public static void getFieldVal(Supplier<?> supplier) {
    return supplier.get();

couponInfo::getCountIt’s just one.supplierBased on this principle, many of the functions that can only be achieved by reflection in the past can be achieved in Java 8Method referenceTo achieve.
Above, even without Java 8, you can gracefully implement these functions with guava.
Reference material:

  1. http://ifeve.com/google-guava/
  2. http://www.importnew.com/1036&#8230;
  3. http://www.importnew.com/1190&#8230;
Border town answered 3 years ago

In fact, Java 8 does not need zip.

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

Find the corresponding set is empty

List<String> result = IntStream.range(0, descArray.length)
        .filter(i -> codeList.get(i) == null)
        .mapToObj(i -> descArray[i])

Correlation Map

Map<String, Integer> codeCountMap = IntStream.range(0, descArray.length)
                i -> codeList.get(i),
                i -> descCouponInfoMap.get(descArray[i]).getCount()));

Generate Map

Map<String, String> descCodeMap = IntStream.range(0, descArray.length)
                i -> descArray[i],
                i -> codeList.get(i)));

Obviously this is your problem.
Do you know what classes and objects are?
Everything uses list map, of course not.
You define a coupon class with code and desc attributes
List<Ticket> ticketList;
for(Ticket ticket:ticketList){


Neither the second nor the third.

dyr11 answered 3 years ago

The deficiency of high-rise design can not be compensated by the bottom.

hl4 answered 3 years ago

Building owners need to strengthen abstract design and data structure design.
In the first scenario, location is a very unstable design. There should be specific types

class Coupon {
   Int id; // corresponding position, guaranteeing no repetition and no dislocation.
   String desc;
   String code;
   public boolean notUsed() {
       return code == null;

This makes it easier to find code empty in a List, but better still, save all notUsedCoupons with an unused List.
In the second scenario, as classification statistics, there are ready-made grouping methods in guava. After grouping is constructed, the number of each group will be known.
In the third scenario, it is not necessary to extract an attribute from each other. In fact, it is possible to construct an object reference to Foo and Bar, using delegation to each other.
These two objects.
As the respondent mentioned above, there is a lack of high-level design. When there are three attributes a, B and c, if you design three lists separately, then there will be
A – > b, B – > C search process, a more complex operation is also a – > (b, c). If they are in an object, then as long as a – > O (a, b, c)
To complete most of the data indexing work.

hsfzxjy answered 3 years ago

Python is an interpreted language that dynamically retrieves properties at runtime
I don’t know much about java, but there should be a number of reflection mechanisms.

yangfeng answered 3 years ago

As an old language, if you say that Java is not expressive enough, why is it the most popular language in the world? It’s just that you don’t learn it well.

laughingcoffin answered 3 years ago

Don’t use arrays or lists to separate tickets and codes. Tickets and codes should be one-to-one. When building a model, you can create a class of tickets, which has code attributes, so it’s very clear?

purpleSky answered 3 years ago

Java is a verbose language, and the code written in Java is basically verbose (before 8).
Java is not as elegant as pyhton and other languages in dealing with basic operations alone, but it can be compensated for by tool classes and other Groovies.