【问题标题】:Use HashSet to weed out duplicate values. List returns either empty or returns duplicate values使用 HashSet 清除重复值。列表返回空值或返回重复值
【发布时间】:2020-06-21 12:44:12
【问题描述】:

我正在尝试使用HashSetArrayList 中删除重复值,这样如果城市名称相同,则不会多次返回它们......列表返回空或仍然显示重复值。希望有人能告诉我代码中的错误在哪里,这样就不会返回重复的值...

我以此作为参考:

Set<String> set = new HashSet<>(yourList); yourList.clear(); yourList.addAll(set); ,但不知道如何使它在我的代码中工作。知道这可能是一个简单的修复,但我一直在玩它,但仍然没有恢复正确......

谁能告诉我这里哪里出错了?到目前为止,根据每个人的说法,代码看起来应该可以工作......虽然它不是......

SearchCityFragment

public class SearchCityFragment extends Fragment {

    private List<Post> mPostList;
    private Set<Post> mPostSet;
    private RecyclerView mRecyclerView;
    private CityAdapter mCityAdapter;

    private EditText mSearchBar;
    private RelativeLayout mRelativeLayout;
    private Activity mActivity;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_search_city, container, false);

        mRelativeLayout = view.findViewById(R.id.relative_layout_11);
        mRelativeLayout.setVisibility(View.VISIBLE);

        mRecyclerView = view.findViewById(R.id.recycler_view);
        mRecyclerView.setHasFixedSize(true);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        mRecyclerView.setLayoutManager(linearLayoutManager);

        mPostList = new ArrayList<>();
        mCityAdapter = new CityAdapter(getContext(), mPostList);
        mRecyclerView.setAdapter(mCityAdapter);

        mSearchBar = mActivity.findViewById(R.id.search_bar);
        mSearchBar.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                searchCity(s.toString().toLowerCase());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        return view;
    }

    private void searchCity(String s) {
        Query query = FirebaseDatabase.getInstance().getReference("Posts").orderByChild("city").startAt(s).endAt(s + "\uf8ff");
        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                mPostList.clear();
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    Post post = snapshot.getValue(Post.class);
                    if (s.length() == 0) {
                        mPostList.clear();
                        mRelativeLayout.setVisibility(View.VISIBLE);
                    } else {
                        mRelativeLayout.setVisibility(View.GONE);
                        mPostList.add(post);
                        mPostSet = new HashSet<>(mPostList);
                        mPostList.clear();
                        mPostList.addAll(mPostSet);
                        readCity();
                    }
                }

                mCityAdapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }

    private void readCity() {
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");
        reference.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if (mSearchBar.getText().toString().equals("")) {
                    mPostList.clear();
                    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                        Post post = snapshot.getValue(Post.class);
                        mPostList.add(post);
                        mPostSet = new HashSet<>(mPostList);
                        mPostList.clear();
                        mPostList.addAll(mPostSet);
                    }

                    mCityAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        if (context instanceof Activity) {
            mActivity = (Activity) context;
        }
    }
}

【问题讨论】:

  • 鉴于mPostSet 是一个成员变量,我可以相信这是某种竞争条件或线程干扰。尝试对集合使用局部变量。
  • 考虑使用LinkedHashSet,以便在mPostList 中获得可预测的排序。
  • @AndyTurner 是我写的逻辑吗?它“应该”工作是否有意义?
  • @AndyTurner 局部变量不起作用...结果相同...取回重复...
  • 看起来应该可以了;尽管每次添加元素时都这样做,但if (!list.contains(thing)) list.add(thing); 会更容易;或将重复数据删除推迟到循环之后。

标签: java android arraylist hashset


【解决方案1】:

如果您只想显示带有搜索城市的帖子,并且只想显示一个这样的帖子,您可以在数据库中查询该城市的帖子,您不需要创建任何数组列表或哈希图。

                          private void searchCity(String s) {
                               FirebaseDatabase.getInstance()
                                     .getReference("Posts")
                                     .orderByChild("city")
                                     .startAt(s)
                                     .limitToFirst(1).
                                     .addValueEventListener(new ValueEvnetListener){
                                     @Override
                                     public void onDataChange(DataSnapshot 
                                     dataSnapshot) {
                                     // do your rhing
                                      }
                                    @Override
                               public void onCancelled(DatabaseError databaseError) {}
                                    } ;
}

【讨论】:

  • 在这种情况下什么是 searchedCity?这是 Query 的变量名吗?
  • 搜索的城市,正如您告诉我的,您的用户正在搜索一个城市,并且您想显示该城市的一篇文章
  • 不是查询变量的名称,你可以创建一个查询变量的想法,我只是链接每个人
  • 是的,但是用户搜索的位置是一个城市,例如,每个帖子都有一个与之关联的城市...如果有多个纽约,例如纽约应该只回来一次......那个城市可以是任何城市,所以我需要“searchedCity”作为查询数据库中所有城市的变量,并确保只有一个具有该特定名称的城市回来,即使有更多不止一个。
猜你喜欢
  • 2018-06-25
  • 1970-01-01
  • 1970-01-01
  • 2018-01-18
  • 2021-12-25
  • 2018-09-08
  • 2015-09-21
  • 2015-07-25
  • 2018-03-01
相关资源
最近更新 更多