How to implement row column conversion in Java of interview question series 56? How to realize column to row conversion?

Posted by jnmunsey on Thu, 13 Jan 2022 02:47:58 +0100

I Interview questions and analysis

1. Today's interview question

How to implement row to column conversion in Java?

How to realize column to row conversion?

2. Topic analysis

The topic that Yige explained to you today is somewhat different from the previous topic. So what's the difference? Let's carefully recall the previous interview questions. You will find that many of the previous questions were mainly based on memory, understanding and bottom exploration, but today's questions are actually based on providing ideas and solutions to solve problems.

During the interview, we may meet a variety of interviewers. These interviewers have their own style and their questioning angles are also different. Some people like to ask for knowledge, some like to ask for project details, and others like to ask for solutions. Today's topic is to investigate the job seekers' ideas and thinking to solve problems and see whether they have pioneering ideas to solve problems. In fact, this ability is more important for us to do projects. So many interviewers will throw questions like this to job seekers: have you ever met xxx? How did you solve this situation? If you encounter xxx problem, how should you solve it? What ideas do you have

For such questions, on the one hand, the interviewer is investigating whether we have experienced such problems, so that we can judge our experience level; On the other hand, in fact, it is more about our thinking and logic ability. In fact, the answer to this question is not unique, and there is no fixed standard answer. It mainly depends on whether we dare to think, whether we can think, and whether we think! Some job seekers, when they encounter similar problems, feel that they have never encountered such a situation, and then think about it without thinking. They directly give the interviewer a sentence: I haven't encountered it, I don't know

If you answer the question like this, what do you think the interviewer will think? How would you judge you? You may not have encountered a certain situation, but you must have your own ideas and solutions. This solution may not be correct, but you have to give your own ideas! Otherwise, I'll recruit you to the project team in the future. If you encounter a problem, tell the boss that I haven't encountered this situation before. I can't do it. Why did the company spend so much money to recruit you?! To hear what you don't know?

II Reference answer

1. Demand background

The requirements of row to column and column to row are generally encountered when making table effects. The common ones are excel report statistics, import and export of Excel files, etc.

For row to column or column to row, our implementation scheme can be considered and implemented from three dimensions:

  1. SQL query is used to encapsulate the required row and column sets directly during query;
  2. In the back-end code, the queried data set is transferred to the necessary line;
  3. The back end directly sends the result set to the front end, and the front end transfers rows and columns to each other.

In this example, the second implementation scheme will be adopted, that is, Java back-end code will be used to convert the queried data set.

2. Effect before conversion

Here, I first wrote a paging effect page with LayUI. The following is the effect picture before row column conversion:

As can be seen from the figure, id, name, address, gender and other data are displayed in one line. At this time, the JSON data format returned by the front end from the back end is as follows:

{
	"code": 0,
	"msg": "success",
	"count": 14,
	"data": [{
		"id": 3,
		"username": "Yiyi brother",
		"address": "Shanghai",
		"sex": "male"
	}, {
		"id": 4,
		"username": "Yige",
		"address": "Shanghai",
		"sex": "male"
	},......]
}

This is the effect after formatting with JSON formatting tool.

It can be seen that the fields such as id, username, address and sex are encapsulated in a json object at the same time. Next, we need to transform the data in this table from row to column, so how to achieve it? Brother Yi has provided the core code to you. You can refer to the following content.

3. Code conversion

The following is the key code to realize row to column conversion. You can refer to the implementation.

3.1 User class

In order to facilitate data encapsulation, I will define a User class here, which will be operated during row column conversion later.

@Data
@ToString
public class User {

    private Integer id;

    private String username;

    private String address;

    private String sex;

}

3.2 line transfer to core category

I defined the operation of row column conversion in the service layer. You can customize the core code of row column conversion according to your own needs.

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private com.yyg.boot.mapper.UserMapper userMapper;

  	//The PageHeper paging class is used in this case. It has nothing to do with row column conversion, but you can remove the contents of PageHelper in order to achieve paging effect.
    @Override
    public PageInfo<User> findUsers(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> list = userMapper.findUsers();

        //Perform row column conversion and call the encapsulated row column conversion code
        List convertList = convert(User.class, list);
        return new PageInfo<User>(convertList);
    }

    /**
     * The implementation method of encapsulating row to column conversion mainly uses reflection to value the fields of JavaBean s in the collection
     */
    public <T> List convert(Class<T> clazz, List<T> list) {
      	//Gets all fields in the bytecode
        Field[] fields = clazz.getDeclaredFields();
      	//Create an empty List collection in which another List collection is nested
        List<List> result = new ArrayList<>(fields.length);
        for (int i = 0; i < fields.length; i++) {
          	//Add several empty List collections
            result.add(new ArrayList());
        }

        for (T t : list) {
            for (int i = 0; i < fields.length; i++) {
              	//Take out each List set
                List l = result.get(i);
                Field field = fields[i];
                field.setAccessible(true);
                try {
                  	//Add the data in the field to the collection
                    l.add(field.get(t));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }

        return result;
    }

}

4. Effect after conversion

After conversion, the JSON data format obtained is as follows:

{"code":0,"msg":"success","count":4,
 "data":[[3,4,5,7,9,11,14,15,16,18],
         ["Yiyi brother","Yige","One brother","One brother","One brother","One brother","One brother","One brother","11 brother 22","11 brother 22"],
         ["Shanghai","Shanghai","Shanghai","Shanghai","Shanghai","Shanghai","Shanghai","Shanghai","Shanghai","Shanghai"],
         ["male","male","male","male","male","male","male","male","male","male"]]}

Use the JSON formatting tool to format the above JSON, and the results are shown in the following figure:

At this time, we will find that the internal data of the data array in JSON is completely different from the previous data. The front end only needs to render the page according to the new JSON array.

III epilogue

In addition, for column to row conversion, please refer to my code for reverse processing.

In fact, the answer to today's question is not the only one. Brother one can only provide you with some reference implementations here. You may have better solutions, even if you have better solutions. If you have better solutions, please leave a message to me in the comment area.

Topics: Java Interview