Try to convert map object to JSONArray rather than JSON Object. It would give you JSONObject to work with directly.

public void getResult(Object result) {
        ObjectMapper mapper = new ObjectMapper();
        Object map = null;
        try {
            map = mapper.readValue((String) result, Object.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        JSONArray json = (JSONArray) map;
        for (int i=0; i < json.length(); i++) {
            JSONObject e = json.get(i);

            System.out.println(e);
        }
}
Answer from vijay on Stack Overflow
Top answer
1 of 3
1

So, you want to return the indexes of first occurrences of distinct items?

Maps can be really cool for these things, and in this case, all you want to actually remember is when was the first occurrence of each distinct element.

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

public class DistinctValues {
    public static List<Integer> distinctIndexes(String[] strings) {

        // holds the mapping { string => index of first occurence of that string }
        Map<String, Integer> firstOccurenceMap = new HashMap<String, Integer>();

        // do a scan through all the items
        for (int i = 0; i < strings.length; i++) {
            // store the index position of a string only if you haven't encountered it before
            firstOccurenceMap.putIfAbsent(strings[i], i);
        }

        return new ArrayList<Integer>(firstOccurenceMap.values());
    }

    public static void main(String[] args) {
        String[] strings = new String[] { "1", "1", "3", "3", "3", "3", "3", "3" };

        System.out.println(distinctIndexes(strings));
    }
}

The output:

[0, 2]
2 of 3
1

This is a simple way of doing it:

String[] temp2 = new String[]{"1", "1", "3", "1", "3" };
List<String> values = new ArrayList<>();
List<Integer> indices = new ArrayList<>();
for( int i = 0; i < temp2.length; ++i ){
    String s = temp2[i];
    if( ! values.contains( s ) ){
        values.add( s );
        indices.add( i );
    }
}

You can now create arrays from the Lists:

String[] uniq = values.toArray(new String[values.size()]);
Integer[] inds = indices.toArray(new Integer[indices.size()]);
🌐
Study.com
study.com › business courses › java programming tutorial & training
Java: Associative Arrays - Lesson | Study.com
August 28, 2019 - In that sense, it's an alternative to the associative array. We can add items to the array using the put method, and pull items using get. In order to display all values, use the keySet function. Objects are removed from ...
🌐
Mkyong
mkyong.com › home › java › java – get keys from value hashmap
Java – Get keys from value HashMap | mkyong.com
February 26, 2021 - private static Optional<List<String>> ... If the HashMap only has one item, we can use map.keySet().toArray() to convert the Set to an Array and [0] to get the first item from the array, which means the first key from the ...
🌐
Coderanch
coderanch.com › t › 370276 › java › key-values-arraylist
how to get the key values from a arraylist (Java in General forum at Coderanch)
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums · this forum made possible by our volunteer staff, including ... ... hello everyone i hope someone can help me i have this arraylist called arr arr.add(1, "ben"); how would i get the number one out of it?
🌐
Techie Delight
techiedelight.com › home › java › get key from value in a java map
Get key from value in a Java Map | Techie Delight
July 7, 2026 - The idea is to extend the HashMap class and overload its put() method such that it also inserts the value-key pair into a reverse map along with the key-value pair in the original map.
🌐
Stack Overflow
stackoverflow.com › questions › 71170305 › how-to-access-key-value-in-array-of-objects-java
How to access key value in array of objects - java - Stack Overflow
I've dealed with JSON values recently. But ended up just using regex and splitting/matching from there. You can regex everything from the "name" (not including until the last comma) and do the same for sport Access. Be aware that this is just a work around, and not the best option. But sometimes JSON objects on Java can be Tricky.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › java › implementing-associate-array-in-java
Implementing Associate Array in Java - GeeksforGeeks
July 23, 2025 - In Java, it is difficult to form the associative array however this could easily be achieved using a HashMap: ... Map<String, String> map = new HashMap<String, String>(); // method to add the key,value pair in hashmap map.put("geeks", "course"); map.put("name", "geeks"); // method to get the value map.get("name"); // returns "geeks"
🌐
Baeldung
baeldung.com › home › json › get a value by key in a jsonarray
Get a Value by Key in a JSONArray | Baeldung
January 8, 2024 - In this tutorial, we’ll be using JSON-Java (org.json) library and learn how to process a JSONArray to extract value for a given key. If needed, we have available an introduction to this library. We’ll first start by adding the below dependency in our POM: <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20240303</version> </dependency> We can always find out the latest version of JSON-Java on Maven Central. A JSON message is usually comprised of JSON objects and arrays which may be nested inside one another.
🌐
Coderanch
coderanch.com › t › 744956 › java › key-JSONArray
Get key:value from JSONArray (Java in General forum at Coderanch)
Take values from JSON file, and store that values into ArrayList, then sort it. The problem is that my json is array, and i do not know how to get just one pair, what is wrong with my code, can you help me?Please.
🌐
W3Schools
w3schools.com › java › java_hashmap.asp
Java HashMap
A HashMap stores items in key/value pairs, where each key maps to a specific value. It is part of the java.util package and implements the Map interface. Instead of accessing elements by an index (like with ArrayList), you use a key to retrieve its associated value.
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-convert-two-arrays-containing-keys-and-values-to-hashmap-in-java
How to Convert Two Arrays Containing Keys and Values to HashMap in Java? - GeeksforGeeks
July 23, 2025 - The insertion order s not preserved in the HashMap. In a HashMap, keys and values can be added using the HashMap.put() method. We can also convert two arrays containing keys and values into a HashMap with respective keys and values.
Top answer
1 of 16
672

If your data structure has many-to-one mapping between keys and values you should iterate over entries and pick all suitable keys:

public static <T, E> Set<T> getKeysByValue(Map<T, E> map, E value) {
    Set<T> keys = new HashSet<T>();
    for (Entry<T, E> entry : map.entrySet()) {
        if (Objects.equals(value, entry.getValue())) {
            keys.add(entry.getKey());
        }
    }
    return keys;
}

In case of one-to-one relationship, you can return the first matched key:

public static <T, E> T getKeyByValue(Map<T, E> map, E value) {
    for (Entry<T, E> entry : map.entrySet()) {
        if (Objects.equals(value, entry.getValue())) {
            return entry.getKey();
        }
    }
    return null;
}

In Java 8:

public static <T, E> Set<T> getKeysByValue(Map<T, E> map, E value) {
    return map.entrySet()
              .stream()
              .filter(entry -> Objects.equals(entry.getValue(), value))
              .map(Map.Entry::getKey)
              .collect(Collectors.toSet());
}

Also, for Guava users, BiMap may be useful. For example:

BiMap<Token, Character> tokenToChar = 
    ImmutableBiMap.of(Token.LEFT_BRACKET, '[', Token.LEFT_PARENTHESIS, '(');
Token token = tokenToChar.inverse().get('(');
Character c = tokenToChar.get(token);
2 of 16
244

If you choose to use the Commons Collections library instead of the standard Java Collections framework, you can achieve this with ease.

The BidiMap interface in the Collections library is a bi-directional map, allowing you to map a key to a value (like normal maps), and also to map a value to a key, thus allowing you to perform lookups in both directions. Obtaining a key for a value is supported by the getKey() method.

There is a caveat though, bidi maps cannot have multiple values mapped to keys, and hence unless your data set has 1:1 mappings between keys and values, you cannot use bidi maps.


If you want to rely on the Java Collections API, you will have to ensure the 1:1 relationship between keys and values at the time of inserting the value into the map. This is easier said than done.

Once you can ensure that, use the entrySet() method to obtain the set of entries (mappings) in the Map. Once you have obtained the set whose type is Map.Entry, iterate through the entries, comparing the stored value against the expected, and obtain the corresponding key.


Support for bidi maps with generics can be found in Google Guava and the refactored Commons-Collections libraries (the latter is not an Apache project). Thanks to Esko for pointing out the missing generic support in Apache Commons Collections. Using collections with generics makes more maintainable code.


Since version 4.0 the official Apache Commons Collections™ library supports generics.

See the summary page of the "org.apache.commons.collections4.bidimap" package for the list of available implementations of the BidiMap, OrderedBidiMap and SortedBidiMap interfaces that now support Java generics.