Common class for indexing an array to a map by IDs

array map
javascript map array of objects
javascript array
array reduce
jquery map
javascript foreach
array filter
javascript map object

I got lot of cases in my code where I have to access data from a DB using Hibernate and receive the results as a list. Most often this data is cached and accessed by ID. So obviously, I have to convert it into a Map for quick results, as iterating over it every time would be an O(n) nightmare.

The question isn't how to do that, the process is fairly trivial:

Map<Integer, ProjectEntry> projectEntries = new HashMap<>();
for (ProjectEntry p : projectService.listProjectEntries()) {
    projectEntries.put(p.getId(), p);

What I wonder is if there's already a feature for this in common Java libraries, because I have to repeat this code over and over and would love to reduce it to a single line. It seems like such a common use case.

The answer by sajib might be the proper one if the built-in functionality of Hibernate already can solve this for you.

Otherwise, such a map can be created using the built-in functionality of the Java standard API - namely, using the appropriate Collector:

Map<Integer, ProjectEntry> map =
    Collectors.toMap(ProjectEntry::getId, Function.identity()));

But of course, this is clumsy. You could pull it out into a utility method. And this utility method could be rather generic, wrapping the line shown above, with a minor specialization for the ProjectEntry class.

A small example:

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

public class MapById
    static class ProjectEntry
        int getId()
            return System.identityHashCode(this);
    public static void main(String[] args)
        List<ProjectEntry> list = new ArrayList<ProjectEntry>();
        list.add(new ProjectEntry());
        list.add(new ProjectEntry());
        list.add(new ProjectEntry());


    private static Map<Integer, ProjectEntry> createMapFromIds(
        Collection<? extends ProjectEntry> collection)
        return createMap(collection, ProjectEntry::getId);

    private static <K, T> Map<K, T> createMap(
        Collection<? extends T> collection, 
        Function<? super T, ? extends K> keyMapper)
            Collectors.toMap(keyMapper, Function.identity()));

Indexed collections, Otherwise, an array with a single element (the provided value) will be created. A common operation is to iterate over the values of an array, processing each one in some way. map(callback[, thisObject]) returns a new array of the return value Classes. Class fields · constructor · extends · static. Errors. var new_array = arr .map (function callback (currentValue [, index [, array]]) { // Return element for new_array } [, thisArg ]) Function that produces an element of the new Array, taking three arguments: The current element being processed in the array. The index of the current element being processed in the array. The array map was called upon.

You can try with this:

Query query=session.createSQLQuery(sql);
List<Map<String,Object>> dataList = query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list(); 

How to simplify your codebase with map(), reduce(), and filter() in , Indexing an array of objects (lookup table). Instead of processing the whole array for finding a user by id, we can construct an object where the  Every variable in MATLAB® is an array that can hold many numbers. When you want to access selected elements of an array, use indexing. For example, consider the 4-by-4 magic square A: There are two ways to refer to a particular element in an array. The most common way is to specify row and column subscripts, such as.

.map(), Description: Pass each element in the current matched set through a function, producing a new If you wish to process a plain array or object, use the jQuery.​map() instead. which contains an array, it's very common to call .get() on the result to work with a basic array. To get a comma-separated list of checkbox ID s:  The map () method creates a new array with the results of calling a function for every array element. The map () method calls the provided function once for each element in an array, in order. Note: map () does not execute the function for array elements without values. Note: this method does not change the original array. Browser Support.

4 Uses of JavaScript's You Should Know ―, is a very powerful method in JavaScript. Here's 4 However, one of the more popular methods is the .map() method. .map() This component is rendered using ReactDOM on the DOM element with id of root. The class contains an array temps of type float[] to store the temperature values. By implementing an indexer in this class, clients can access the temperatures in a TempRecord instance as float temp = tr[4] instead of as float temp = tr.temps[4]. The indexer notation not only simplifies the syntax for client applications; it also makes the

Array methods, In real life arrays of objects is a common thing, so the find method is very useful. we provide to find the function item => == 1 with one argument. let result = arr . map ( function ( item , index , array ) { // returns the  First, let’s review how you transform lists in JavaScript. Given the code below, we use the map () function to take an array of numbers and double their values. We assign the new array returned by map () to the variable doubled and log it: This code logs [2, 4, 6, 8, 10] to the console. In React, transforming arrays into lists of elements is

Deep Dive into JavaScript's Array Map Method, Specifically, the Array Map Method operates on an array to run a syntax for the callback function in a Map Method is very common, mainly because it Here are the three arguments that it takes:, index, array) => { . where each key represents a unique id, but all of the values might be a  This use is not an integer position along the index.). A list or array of labels ['a', 'b', 'c']. A slice object with labels 'a':'f' (Note that contrary to usual python slices, both the start and the stop are included, when present in the index! See Slicing with labels. A boolean array. A callable, see Selection By Callable.

  • Write it yourself as a method and then invoke that method. It's on a single line now.
  • I've already outsourced it to a utility class, but I can't believe there's no commons library to already support this. That was my question.
  • You mean getting a map straight from Hibernate?
  • Does Hibernate already support that? I always get the results by invoking .list() at a Hibernate Criteria.
  • There is no projectService.getProjectEntryById? Generally hibernate already caches.