1. 程式人生 > >簡析Map及Map集合的遍歷解析、排序

簡析Map及Map集合的遍歷解析、排序

先上效果圖:

     

(效果圖中的資料皆來自Map)

扯點犢子:

其實Android對Java基礎的要求並不高,雖然Android是基於Java的,但是Android有更多它自己的東西。

但是對於Java基礎還是需要充分的瞭解,這會對你的開發事半功倍,就像英語不好的開發者一樣可以看懂程式碼,但是英語好的開發者效率一定比英語不好的高。

一、Map

Map是以鍵值對的方式進行資料讀寫且無序,底層是通過key的hashCode計算hash值,根據hash值得到位置索引,  然後對該位置索引進行讀寫。



HashMap

HashMap是基於雜湊表的Map介面的非同步實現。此實現提供所有可選的對映操作,並允許使用null值和null鍵。

HashMap底層就是一個數組結構,陣列中的每一項又是一個連結串列。



二、實戰

1.資料來源

//新增資料

        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)效果圖一。

//把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是從前向後新增的,也就是最後新增的資料在陣列的最前面。

//遍歷得到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

<?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
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
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
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;
    }

}