【问题标题】:merge two lists of different objects合并两个不同对象的列表
【发布时间】:2021-09-10 23:56:29
【问题描述】:

我正在使用返回列表的 api 请求。 - 第一个 api 请求返回一个包含 (user_id,content,date,title) 的对象列表 - 第二个响应也返回包含 (user_id,user_name) 的对象列表。

我想合并这两个列表并将它们显示到一个回收器视图中,但保留用户名而不是 user_id。这张图片清楚地分解了我想要的内容。

感谢任何帮助,我真的陷入了困境,我需要它。

编辑

这是第一个 api 调用:

    followuplist=new ArrayList<>();


    Retrofit retrofit = RetrofitInstance.getRetrofitInstance();
    final Api api = retrofit.create(Api.class);
    Call<List<TraitementTicketModel>> call = api.getfollowup(id, sestoken);
    call.enqueue(new Callback<List<TraitementTicketModel>>() {

        @Override
        public void onResponse(Call<List<TraitementTicketModel>> call, Response<List<TraitementTicketModel>> response) {
            if (!response.isSuccessful()) {
                Toast.makeText(getApplicationContext(), "Something is wrong !! ", Toast.LENGTH_LONG).show();
                Log.e("TAG", "onResponse: something is wrong");


            } else if (response.body() == null) {

                return;
            }

            List<TraitementTicketModel> followups = response.body();


            for (TraitementTicketModel followup : followups) {


                followuplist.add(followup);

            }


            followuplist.add(firstfollowup());
           

        }

        @Override
        public void onFailure(Call<List<TraitementTicketModel>> call, Throwable t) {
            Toast.makeText(getApplicationContext(),"Pas de connextion internet",Toast.LENGTH_LONG).show();
        }
    });

这是第二个 api 调用:

      List<User> userList;
      SharedPreferences sp =getApplicationContext().getSharedPreferences("tokenPref", Context.MODE_PRIVATE);
    String sestoken = sp.getString("token","");

    Retrofit retrofit= RetrofitInstance.getRetrofitInstance();
    final Api api= retrofit.create(Api.class);
    Call<List<User>> call = api.getUser(sestoken);
    call.enqueue(new Callback<List<User>>() {
        @Override
        public void onResponse(Call<List<User>> call, Response<List<User>> response) {

            if (response.code() != 200){
                Log.e("TAG", "onResponse: something is wrong"+response.code() );



            }
            List<User> users = response.body();



            for (User user : users){

                userList.add(user);
            }

            swipeRefreshLayout.setRefreshing(false);



        }

所以我有两个列表第一个是: 后续列表(用户 ID、标题、内容、日期) 第二个: 用户列表(用户 ID,用户名) 但我不知道在那之后该怎么做才能达到我的目标

【问题讨论】:

  • 你到底在坚持什么,到目前为止你做了什么?
  • 发布您解决此问题的最佳尝试。
  • 好的,我要编辑这个
  • 如果你不能运行一次调用来获取你需要的信息(在 SQL 中很容易加入 user_id 以在一次调用中一次获取所有数据),那么你应该组织一个列表中的一个映射,其中 user_id 是键,对象是值。然后很容易遍历列表,在地图上查找并创建您的组合对象,但同样,这似乎是一个应该由 API 解决的问题,

标签: java android list object merge


【解决方案1】:

你可以做这样的事情。 在此示例中,UserDetails 是图像左侧的对象,UserInfo 是右侧的对象,MergeData 是结果。

您应该使用 Kotlin 而不是 Java,操作列表要容易得多。

 List<MergedData> mergeList(
            List<UserDetails> listUserDetails,
            List<UserInfo> listUserInfo
    ) {

        // Resulting list
        final List<MergedData> result = new ArrayList<>();
        // We iterate through the first list
        for (UserDetails details : listUserDetails) {
            // For each element of the list we will try to find one with the same user id in the other list
            for (UserInfo info : listUserInfo) {
                // if the current element of the second list has the same user id as the current one from the first list, we merge the data in a new object and this object is then added to the result list.
                if (details.getUserId().equals(info.getUserId())) {
                    result.add(
                            new MergedData(
                               info.getName(),
                               details.getContent(),
                               details.getTitre(),
                               details.getDate()
                            )
                    );
                    // Once the object is found it is unnecessary to continue looping though the second list, so we break the for loop.
                    break;
                }
            }
        }
        // Once we finished to iterate through the first list, we return the result.
        return result;
    }

Kotlin 中的相同示例:

fun mergeList(
    listUserDetails: List<UserDetails>,
    listUserInfo: List<UserInfo>
): List<MergedData> =
    listUserDetails.mapNotNull { details ->
        listUserInfo
            .firstOrNull { it.userId == details.userId }
            ?.let { info ->
                MergedData(
                    info.name,
                    details.content,
                    details.titre,
                    details.date
                )
            }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-08
    • 2018-04-21
    • 2019-06-09
    • 2022-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多