Java Array to Map toMap(String[][] strings)

Here you can find the source of toMap(String[][] strings)

Description

Create a map from an array of string arrays as follows:

For {{key1, value1}, {key2, value2}, ...}, create a map of the keys to values.

License

Open Source License

Declaration

public static final Map<String, String> toMap(String[][] strings) 

Method Source Code

//package com.java2s;
/*//  w  ww .j  a  va  2s . c om
  Copyright 2009 Semantic Discovery, Inc. (www.semanticdiscovery.com)
    
  This file is part of the Semantic Discovery Toolkit.
    
  The Semantic Discovery Toolkit is free software: you can redistribute it and/or modify
  it under the terms of the GNU Lesser General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.
    
  The Semantic Discovery Toolkit is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU Lesser General Public License for more details.
    
  You should have received a copy of the GNU Lesser General Public License
  along with The Semantic Discovery Toolkit.  If not, see <http://www.gnu.org/licenses/>.
  */

import java.util.HashMap;

import java.util.Map;

public class Main {
    /**
       * Create a map from an array of string arrays as follows:
       * <p>
       * For {{key1, value1}, {key2, value2}, ...}, create a map of the keys
       * to values. Ignore array elements with fewer than 2 entries, map
       * pairs of even elements when there are 2 or more elements and
       * ignore extra (odd) array elements.
       */
    public static final Map<String, String> toMap(String[][] strings) {
        final Map<String, String> result = new HashMap<String, String>();

        for (String[] array : strings) {
            for (int i = 0; i < array.length - 1; i += 2) {
                result.put(array[i], array[i + 1]);
            }
        }

        return result;
    }

    /**
       * Create a map from an array of strings of the form:
       * <p>
       * {key1, value1, key2, value2, ...}
       * <p>
       * NOTE: extra (odd) entries will be ignored.
       */
    public static final Map<String, String> toMap(String[] strings) {
        final Map<String, String> result = new HashMap<String, String>();

        for (int i = 0; i < strings.length - 1; i += 2) {
            result.put(strings[i], strings[i + 1]);
        }

        return result;
    }
}

Related

  1. toMap(String... keysAndValues)
  2. toMap(String[] keyNames, T[] values)
  3. toMap(String[] keys)
  4. toMap(String[]... wordMappings)
  5. toMap(String[][] checksumsArray)
  6. toMap(T[][] pairs)
  7. toMap(T[][] ts)