简析Map及Map集合的遍历解析、排序

2022-06-10 11:16:21 浏览数 (1)

先上效果图:

(效果图中的数据皆来自Map)

扯点犊子:

其实Android对Java基础的要求并不高,虽然Android是基于Java的,但是Android有更多它自己的东西。

但是对于Java基础还是需要充分的了解,这会对你的开发事半功倍,就像英语不好的开发者一样可以看懂代码,但是英语好的开发者效率一定比英语不好的高。

一、Map

Map是以键值对的方式进行数据读写且无序,底层是通过key的hashCode计算hash值,根据hash值得到位置索引,  然后对该位置索引进行读写。

HashMap

HashMap是基于哈希表的Map接口的非同步实现。此实现提供所有可选的映射操作,并允许使用null值和null键。

HashMap底层就是一个数组结构,数组中的每一项又是一个链表。

二、实战

1.数据源

代码语言:javascript复制
	//添加数据

        map1 = new HashMap<>();
        map1.put(100, 10);
        map1.put(300, 30);
        map1.put(200, 20);
        map1.put(400, 40);

        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < 2; i  ) {
            list.add(" ParseMap "   i);
        }
        map2 = new HashMap<>();
        map2.put(100, list);
        map2.put(200, list);
        map2.put(300, list);

2.遍历并排序

a)效果图一。

代码语言:javascript复制
	//把key转为一个集合
        List<Integer> list = new ArrayList<>(map1.keySet());
        //比较器
        Collections.sort(list, new Comparator<Integer>() {
            @Override
            public int compare(Integer s1, Integer s2) {
                //升序排列 ,降序 把s1 s2调换即可
                return s1.compareTo(s2);
            }
        });

        //遍历得到key和value,添加到集合
        keyList = new ArrayList<>();
        valueList = new ArrayList<>();
        //遍历map的常用方法一
        for (Integer i : list) {
            Log.i("常用方法一", "key = "   i   " , value = "   map1.get(i));
            keyList.add(i);
            valueList.add(map1.get(i));
        }

b)效果图二。

第二种方法没有排序,效果图二中是300、200、100,而数据源添加的顺序是100、200、300,但是显示的效果却是相反的,这是因为Entry是从前向后添加的,也就是最后添加的数据在数组的最前面。

代码语言:javascript复制
	//遍历得到key和value,添加到集合
        keyList = new ArrayList<>();
        valueList = new ArrayList<>();
        //遍历map的常用方法二
        for (Map.Entry<Integer, List<String>> entry : map2.entrySet()) {
            Log.i("常用方法二", "key = "   entry.getKey()   " , value = "   entry.getValue());
            keyList.add(entry.getKey());
            valueList.add(entry.getValue());
        }

三、代码

activity_main.xml

代码语言:javascript复制
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@ id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.yechaoa.parsemap.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@ id/button1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="解析map并排序" />

        <Button
            android:id="@ id/button2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="解析嵌套map" />

    </LinearLayout>

    <GridView
        android:id="@ id/gridView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:columnWidth="90dp"
        android:horizontalSpacing="10dp"
        android:numColumns="2"
        android:scrollbars="none"
        android:stretchMode="columnWidth"
        android:verticalSpacing="10dp"
        android:visibility="gone" />

    <ListView
        android:id="@ id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="10dp"
        android:visibility="gone" />

</LinearLayout>

MainActivity.java

代码语言:javascript复制
package com.yechaoa.parsemap;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button button1;
    private Button button2;
    private GridView gridView;
    private ListView listView;
    private HashMap<Integer, Integer> map1;
    private HashMap<Integer, List<String>> map2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initData();
        initListener();
    }

    private void initView() {
        button1 = (Button) findViewById(R.id.button1);
        button2 = (Button) findViewById(R.id.button2);
        gridView = (GridView) findViewById(R.id.gridView);
        listView = (ListView) findViewById(R.id.listView);
    }

    private void initData() {

        //添加数据

        map1 = new HashMap<>();
        map1.put(100, 10);
        map1.put(300, 30);
        map1.put(200, 20);
        map1.put(400, 40);

        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < 2; i  ) {
            list.add(" ParseMap "   i);
        }
        map2 = new HashMap<>();
        map2.put(100, list);
        map2.put(200, list);
        map2.put(300, list);

    }

    private void initListener() {
        button1.setOnClickListener(this);
        button2.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //为演示效果直接控制样式
            case R.id.button1:
                button2.setTextColor(Color.BLACK);
                button1.setTextColor(Color.RED);
                listView.setVisibility(View.GONE);
                gridView.setVisibility(View.VISIBLE);
                gridView.setAdapter(new GridViewAdapter(this, map1));
                break;
            case R.id.button2:
                button1.setTextColor(Color.BLACK);
                button2.setTextColor(Color.RED);
                gridView.setVisibility(View.GONE);
                listView.setVisibility(View.VISIBLE);
                listView.setAdapter(new ListViewAdapter(this, map2));
                break;
        }
    }

}

GridViewAdapter.java

代码语言:javascript复制
package com.yechaoa.parsemap;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * Created by yechao on 2017/4/21.
 * Describe :
 */

public class GridViewAdapter extends BaseAdapter {

    private Context mContext;
    private Map<Integer, Integer> map1;
    private final List<Integer> keyList;
    private final List<Integer> valueList;

    public GridViewAdapter(Context mContext, Map<Integer, Integer> map1) {
        super();
        this.mContext = mContext;
        this.map1 = map1;

        //把key转为一个集合
        List<Integer> list = new ArrayList<>(map1.keySet());
        //比较器
        Collections.sort(list, new Comparator<Integer>() {
            @Override
            public int compare(Integer s1, Integer s2) {
                //升序排列 ,降序 把s1 s2调换即可
                return s1.compareTo(s2);
            }
        });

        //遍历得到key和value,添加到集合
        keyList = new ArrayList<>();
        valueList = new ArrayList<>();
        //遍历map的常用方法一
        for (Integer i : list) {
            Log.i("常用方法一", "key = "   i   " , value = "   map1.get(i));
            keyList.add(i);
            valueList.add(map1.get(i));
        }
    }

    @Override
    public int getCount() {
        return map1.size();
    }

    @Override
    public Object getItem(int position) {
        return map1.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(this.mContext).inflate(R.layout.item_gridview, parent, false);
            holder = new ViewHolder();
            holder.item_gv_textView1 = (TextView) convertView.findViewById(R.id.item_gv_textView1);
            holder.item_gv_textView2 = (TextView) convertView.findViewById(R.id.item_gv_textView2);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.item_gv_textView1.setText(String.valueOf("充¥"   keyList.get(position)));
        holder.item_gv_textView2.setText(String.valueOf("送¥"   valueList.get(position)));
        return convertView;
    }

    private class ViewHolder {
        TextView item_gv_textView1;
        TextView item_gv_textView2;
    }

}

ListViewAdapter.java

代码语言:javascript复制
package com.yechaoa.parsemap;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yechao on 2017/4/21.
 * Describe :
 */

public class ListViewAdapter extends BaseAdapter {

    private Context mContext;
    private HashMap<Integer, List<String>> map2;
    private List<Integer> keyList;
    private List<List<String>> valueList;

    public ListViewAdapter(Context mContext, HashMap<Integer, List<String>> map2) {
        super();
        this.mContext = mContext;
        this.map2 = map2;

        //遍历得到key和value,添加到集合
        keyList = new ArrayList<>();
        valueList = new ArrayList<>();
        //遍历map的常用方法二
        for (Map.Entry<Integer, List<String>> entry : map2.entrySet()) {
            Log.i("常用方法二", "key = "   entry.getKey()   " , value = "   entry.getValue());
            keyList.add(entry.getKey());
            valueList.add(entry.getValue());
        }
    }

    @Override
    public int getCount() {
        return map2.size();
    }

    @Override
    public Object getItem(int position) {
        return map2.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(this.mContext).inflate(R.layout.item_listview, parent, false);
            holder = new ViewHolder();
            holder.itemLvTitle = (TextView) convertView.findViewById(R.id.item_lv_title);
            holder.itemLvListView = (MyListView) convertView.findViewById(R.id.item_lv_listView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.itemLvTitle.setText(String.valueOf(keyList.get(position)));
        //再把value集合传给嵌套的ListViewSubAdapter
        holder.itemLvListView.setAdapter(new ListViewSubAdapter(mContext, valueList.get(position)));
        return convertView;
    }

    private class ViewHolder {
        TextView itemLvTitle;
        MyListView itemLvListView;
    }

}

完整代码:https://github.com/yechaoa/ParseMap

0 人点赞