Searching Array List by a String - java

One problem that I am facing in my code is that I have a long list of strings that map to different integers. For example, "Apple" maps to 4, "Bat" maps to 7, etc. Is there any ways to create an Array List such that a string is used as the input search element rather than a traditional number? Ie. Array["Apple"] instead of Array[4]

Use an associative data structure for this.
Map<String, Integer> items = new HashMap<>();
items.put("Apple", 4);
items.put("Bat", 7);
items.get("Apple");
items.get("Bat");

ArrayList doesn't have that support. But Hashmaps can solve your usecase. Check that out.

You can use a Map to solve your use case.
Map<String, Integer> fruits = new HashMap<String, Integer>();
Now your fruits Map will have the String as a key and Integer as a value.
To put key-value: fruits.put("Apple", 1)
To get value based on key: fruits.get("Apple")

You will need two data structures for this problem: a Map to associate item names with indices and a List to store the items (e.g. an ArrayList). For example (untested):
// Store the items and a mapping of their indices by name.
List<String> items = new ArrayList<String>();
Map<String, Integer> itemIndices = new HashMap<String, Integer>();
// Add the item to both data structures.
itemIndices.put("Apple", 4);
items.add("Apple", 4);
// Now you can fetch them by name.
items.get(itemIndices.get("Apple")); // => "Apple"
Of course, you can use a Map<String,Integer> directly, with no need for the List...

Related

Store the values without overwriting

I have a Map<String, Integer> e.g.
"aaa", 1
"bbb", 2
"ccc", 3
"aaa", 4
The problem is that the HashMap does not store all key and values, as I've understood, when i try add the last pair ("aaa", 4), it will not be added, instead of this, the value for "aaa" (I mean 1) will be overwritten on 4.
I know, that I could create class, where I could store these pairs, but I need another solution. (without creating a new class)
EDIT ------------------------------------
Actually I have much more pairs, and I do not have uniques String or Integers, I mean that, if even I have two similar pairs they will be stored
A map, by definition, will have distinct keys. If you add a key-value pair and the key already exists, the new key-value pair will overwrite the existing key-value pair.
For your scenario, when you have multiple values against a single key, you can explore the following options
Option 1 : Since your key-value pairs are not unique, it can be stored as list of pairs. For every key-value pair, you can create a pair and insert it into the list.
List<Pair<String, Integer>> data = new ArrayList();
Pair<String, Integer> item = new Pair("abc", 1);
data.add(item);
This option does not give you optimized lookup capabilities that comes with Map.
Option 2. Create a Map<String, List<Integer>>. You'll not be able to do simple put operations on the map anymore, but you will be able to store all the items corresponding to each key without loss of information as well as retrieve them faster.
Create a List:
if (!map.containsKey("aaaa")) {
map.put("aaaa", new ArrayList<Integer>());
}
List<Integer> aaaaValues = map.get("aaaa");
aaaaValues.add(1);
aaaaValues.add(4);
...
If your values are unieque, use them as keys.
You don't have to create class. You can use List<org.apache.commons.lang3.tuple.Pair<String, Integer>>
Also one way, override equals and hashCode where you speak that object is unique only if String and Integer parameter is unique in pair
Map<String, Integer> map = new HashMap<String, Integer>(){
#Override
public boolean equals(Object o)
{
// your realization
}
#Override
public int hashCode()
{
// your realization
}
};

Java 8 filter List of Map objects based on Map property to remove some duplicates

Have a
List<Map<String, Object>> allPoints = new LinkedList<>();
Each map contains a "name" key with a String value;
Need to create a
List<Map<String, Object>> expectedPoints
There are duplicate names in the list; for these, want to keep the last one only.
E.g. if the list has three items, and first and third items both have"name" with value "abc", the resulting list should only contain the second and third items from the original list.
One way to do it is by using an auxiliary map:
Map<String, Map<String, Object>> map = new LinkedHashMap<>(allPoints.size(), 0.75f, true);
allPoints.forEach(point -> map.put((String)point.get("name"), point));
List<Map<String, Object>> expectedPoints = new ArrayList<>(map.values());
This works because Map.put either puts a new entry to the map or overwrites the value of an existing entry with the new one, thus keeping only the last point associated with the name.
I'm creating an access-ordered LinkedHashMap by using its overloaded constructor. This is to maintain the same order as in the allPoints list.
In case you have the constraint on one or more key-value pairs and flexible to use a Set, write your own Comparator and use descendingIterator on LinkedList and write to TreeSet. See code below:
LinkedList<Map<String, Object>> allPoints = new LinkedList<>();
Set<Map<String, Object>> expectedPoints = new TreeSet<>((objectMap1, objectMap2) ->
objectMap2.get("name").equals(objectMap1.get("name")) ? 0 : -1
);
allPoints.descendingIterator().forEachRemaining(expectedPoints::add);

java removing hashmap from arraylist if it does not contain certain key sets

Let's say I have arraylist of Hashmap,
and Hashmap contain some keys and values
Arraylist d = [{key1=1,key2=2},{key1=1,key3=3}]
I want to remove hashmap that does not contain certain key.
for example, I want to remove hashmap that does not have key2.
result should be:
d= [{key=1,key2=2}]
How do I approach this?
If source is
List<Map<String, Integer>> list;
You can filter it that way:
List<Map<String, Integer>> newList =
list.stream().filter(m -> m.containsKey("key2")).collect(Collectors.toList());

Merging a Set and List to HashMap

I have one set whose keys are String and List of type String I want to make a HashMap out of this Set and List. The set contains categories and the list contains places belonging to those categories. Following is what I tried
Set<Entry<String, Integer>> setUserPreferences = sortedUserPreferences.entrySet();
Map<String , Integer> sortedPlaces = new HashMap<String, Integer>();
List<String> topPlaces = new ArrayList<String>();
Map<String , List<String>> finalPlaces = new HashMap<String, List<String>>();
for (Entry<String, Integer> entry : setUserPreferences) {
sortedPlaces = placesService.sortPlaces(categorisedPlaces.get(entry.getKey()));
int counter = 0;
for (Map.Entry<String, Integer> sortedplace : sortedPlaces.entrySet()) {
topPlaces.add(sortedplace.getKey());
counter++;
if(counter == 5){
sortedPlaces.clear();
break;
}
}
finalPlaces.put(entry.getKey(), topPlaces);
topPlaces.clear();
}
First I iterate over the set and for each key I get the sorted Places, out of the sorted places I pick the top 5 places for each category, Finally I put it in the map where the key is the category and value is the list of top 5 places in that category.
I need to clear the topPlaces list for each iteration over the set because I dont want to have the places from one category appear in the other, but once I put the list in map(finalPlaces) and clear the list it also clear the map values.
How can I clear the list without clearing the map values.
Thanks
topPlaces is a reference to an Object, not a primitive. So, if you store it in the map, you have two references to the same Object, one inside the Map and one outside. If you wipe one, you wipe both.
If you want to clear topPlaces without deleting the stored list, you need to copy it before adding it to the Map.
Something like this:
finalPlaces.put(entry.getKey(), new ArrayList<String(topPlaces));

List Object with multiple "keys" in it

Hoi,
currently I have a List in Java where I add Entrys via list.add("Example");
But now I would like to add IDs to each entry. I could do this via
list.put("Example XY");
list.setData("Example XY", 1);
But in my lists there are a lot of duplicate "Names". So they Keys for the names get overriden because it seems that I cant set duplicate keys in it.
Somebody got an Idea how to solve it? Thanks a lot!
You should really think about using a ListViewer instead. A ListViewer can contain any bean object you want and show any of it's fields as the text in the List.
Here is an example of a ListViewer.
It's definitely a lot more code, but it will be worth it in the end.
Use a HashMap, if you would like to store the key - value pair in the collection
import java.util.HashMap;
public class Test1 {
public static void main( String [] args)
{
HashMap<String, String> map = new HashMap<String,String>();
map.put("1", "Example XY");
map.put("2", "Example XZ");
}
}
Note: you can not have duplicate values for key
You should look into MultiMap
Use MultiMap<String, String>
Multimap<String, String> myMultimap = ArrayListMultimap.create();
// Adding some key/value
myMultimap.put("E1", "One");
myMultimap.put("E1", "Two");
myMultimap.put("E1", "Three");
myMultimap.put("E2", "AnotherOne");
// Getting the size
int size = myMultimap.size();
System.out.println(size); // 4
// Getting values
Collection<string> sample = myMultimap.get("E1");
System.out.println(E1); // [One, Two, Three];
Hope this helps.
You have to consider what it means when an object has the same key. If it's not the same object than the key you are using is wrong. You could add the data to the objects instead of using strings and then have a list with multiples of each "name"
List l = new ArrayList<SomeObject>;
list.put(new SomeObject("red ball", 1))
list.put(new SomeObject("red ball", 2))
or make a map of lists of values
Map<String,List<SomeObject>> = new HashMap<String,List<SomeObject>>;
map.get("Red Ball")==null ? map.put(new ArrayList<SomeObject>(){{ add(x) }})
: map.get("Red Ball").add(x);
Personally I prefer solution 1.

Categories

Resources