RxJava: Converting Map<String, CryptoCoin> to List<CryptoCoin> [duplicate] - kotlin

How do I convert a Map<key,value> to a List<value>? Should I iterate over all map values and insert them into a list?

List<Value> list = new ArrayList<Value>(map.values());
assuming:
Map<Key,Value> map;

The issue here is that Map has two values (a key and value), while a List only has one value (an element).
Therefore, the best that can be done is to either get a List of the keys or the values. (Unless we make a wrapper to hold on to the key/value pair).
Say we have a Map:
Map<String, String> m = new HashMap<String, String>();
m.put("Hello", "World");
m.put("Apple", "3.14");
m.put("Another", "Element");
The keys as a List can be obtained by creating a new ArrayList from a Set returned by the Map.keySet method:
List<String> list = new ArrayList<String>(m.keySet());
While the values as a List can be obtained creating a new ArrayList from a Collection returned by the Map.values method:
List<String> list = new ArrayList<String>(m.values());
The result of getting the List of keys:
Apple
Another
Hello
The result of getting the List of values:
3.14
Element
World

Using the Java 8 Streams API.
List<Value> values = map.values().stream().collect(Collectors.toList());

map.entrySet() gives you a collection of Map.Entry objects containing both key and value. you can then transform this into any collection object you like, such as new ArrayList(map.entrySet());

a list of what ?
Assuming map is your instance of Map
map.values() will return a Collection containing all of the map's values.
map.keySet() will return a Set containing all of the map's keys.

I guess you want to convert the values contained in the Map to a list? Easiest is to call the values() method of the Map interface. This will return the Collection of value objects contained in the Map.
Note that this Collection is backed by the Map object and any changes to the Map object will reflect here. So if you want a separate copy not bound to your Map object, simply create a new List object like an ArrayList passing the value Collection as below.
ArrayList<String> list = new ArrayList<String>(map.values());

Map<String, Integer> map = new HashMap<String, Integer>();
map.put("java", 20);
map.put("C++", 45);
Set <Entry<String, Integer>> set = map.entrySet();
List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);
we can have both key and value pair in list.Also can get key and value using Map.Entry by iterating over list.

If you want to ensure the values in the resultant List<Value> are in the key-ordering of the input Map<Key, Value>, you need to "go via" SortedMap somehow.
Either start with a concrete SortedMap implementation (Such as TreeMap) or insert your input Map into a SortedMap before converting that to List. e.g.:
Map<Key,Value> map;
List<Value> list = new ArrayList<Value>( new TreeMap<Key Value>( map ));
Otherwise you'll get whatever native ordering the Map implementation provides, which can often be something other than the natural key ordering (Try Hashtable or ConcurrentHashMap, for variety).

// you can use this
List<Value> list = new ArrayList<Value>(map.values());
// or you may use
List<Value> list = new ArrayList<Value>();
for (Map.Entry<String, String> entry : map.entrySet())
{
list.add(entry.getValue());
}

Map<String, String > map = new HapshMap<String, String>;
map.add("one","java");
map.add("two", "spring");
Set<Entry<String, String>> set = map.entrySet();
List<Entry<String, String>> list = new ArrayList<Entry<String, String>> (set);
for(Entry<String, String> entry : list) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}

Here's the generic method to get values from map.
public static <T> List<T> ValueListFromMap(HashMap<String, T> map) {
List<T> thingList = new ArrayList<>();
for (Map.Entry<String, T> entry : map.entrySet()) {
thingList.add(entry.getValue());
}
return thingList;
}

public List<Object> convertMapToList(Map<Object, Object> map){
return new ArrayList<>(map.values());
}

If you want an immutable copy of the values:
List<Value> list = List.copyOf(map.values())

Related

How to create list with float values in kotlin

I am a beginner in this field, I want to create a list of float values in kotlin
Example: In python
myList=[]
mylist.append(1.5)
mylist.append(2.5)
but how to do this in kotlin
We need to specify the list element's data type (Float in this case) when initializing empty mutable list using mutableListOf().
val myList = mutableListOf<Float>()
myList.add(1.5f)
myList.add(2.5f)
Use the listOf function:
val listOfFloats: List<Float> = listOf(1.1f, 2.2f, 3.3f)
In kotlin you can make a list like this
var myList: List<Int> = listOf<Int>(1, 2, 7, 9);
But if you want to push an item to the list you need to make it a mutable list. So I would say that you use a MutableList instead of a List
So it looks like this
var myList : MutableList<Int> = mutableListOf<Int>(); //You can add initial values inside the parentheses
myList.add(10);
myList.add(20);

Can't use observableArrayList as value of hashmap in kotlin

I am trying to create a hashmap of a generic type to an array list type from FX Collections.
private val items = FXCollections.observableArrayList<T>()
private val itemsData = hashMapOf<T, FXCollections.observableArrayList<ItemData<T>>>()
The first line works fine, the second gives me a red line under 'observableArrayList'.
Unresolved reference: observableArrayList
This also works fine:
private val itemsData = hashMapOf<T, ItemData<T>>()
I'm new to kotlin and javafx, but even if importing observableArrayList directly doesn't help..
You're confusing a type with an object.
FXCollections.observableArrayList is a method that returns an instance of type ObservableList<E>. The declaration of the HashMap needs a type in the generics though.
Give this a try:
val itemsData = hashMapOf<T, ObservableList<ItemData<T>>>();
A simpler example as an explaination:
// delcare that my password storage has a string type as key and a string type as value
val myPasswords = hashMapOf<String, String>();
// add a pair of string instances
myPasswords["stackoverflow.com"] = "topsecret"

copy one arraylist to another arraylist in kotlin

I am trying to copy one ArrayList to another ArrayList in Kotlin
1st ArrayList:
private var leadList1: ArrayList<Lead> = ArrayList()
2nd ArrayList:
val leadList2: ArrayList<Lead?>?
I tried to use addAll(). leadList1.addAll(leadList2)
But its not working.
Error showing:
Required: Collection<Lead>
Found: kotlin.collections.ArrayList<Lead?>?
This isn't safe to do, because your first list can only contain objects of type Lead, while your second one has Lead? as its type parameter, meaning that it might contain null values. You can't add those to the first list.
The solution for this problem will depend on your context, but you can either let the first list contain nullable elements too:
private var leadList1: ArrayList<Lead?> = ArrayList()
Or you can add only the non-null elements of the second list to the first one:
leadList1.addAll(leadList2.filterNotNull())
And in either case, you'll have to perform a null check on leadList2, because the entire list itself is marked as potentially null as well, signified by the last ? of the type ArrayList<Lead?>?.
if (leadList2 != null) {
leadList1.addAll(leadList2.filterNotNull())
}
You can simply pass another List instance into the constructor of your new List
val originalList = arrayListOf(1,2,3,4,5)
val orginalListCopy = ArrayList(originalList)
Do this:
leadList1.addAll(leadList2.orEmpty().filterNotNull())
And to filter by property you can do like this:
leadList1.addAll(leadList2.orEmpty().filter { item -> item?.type == YourTypeString })

How to create an Immutable List that needs to loop through a field of another list

I want to create a List of item from the field within another List of items.
private var destinies: MutableList<String> = ArrayList()
fun createDestinies(sources: List<Source>) {
for (source in sources) {
destinies.add(source.endpoint)
}
}
In order to do that, I need to define my destinies as MutableList, so that I could "add" to it. But I just need the "add" loop once.
Is there a way for me to do that, without need to have a MutableList? (i.e. I prefer an immutable List, since it doesn't need to change after that)
Apparently quite simple as below
private var destinies: List<String> = ArrayList()
fun createDestinies(sources: List<Source>) {
destinies = sources.map { it.endpoint }
}

Get value from Dictionary<String, Any>

I declared a Dictionary<String, Any> which has some Strings, Arrays and ints as values.
When I try to get back a value based on String key, I'm not able to cast it to Array,
even if that value identified by key is a real Array.
let lColorValues = lTabBarDictionary[TabBarKey.tabBarColor] as Array;
p.s. TabBarKey.tabBarColor is a string
Apple's Swift Programming Book offers an example with an Array which store different kinds of objects, and they use as to downcast objects, which seems to work fine for Array but not for Dictionary.
Did I missed something ? How to get values for such Dictionary ?
You have to specify the type the Array holds, for example:
class TabBarKey {
class var tabBarColor : String {
return "key"
}
}
let arr = ["1", "2", "3"]
var lTabBarDictionary = Dictionary<String, Any>()
lTabBarDictionary[TabBarKey.tabBarColor] = arr
let val = lTabBarDictionary[TabBarKey.tabBarColor] as Array<String>
in the last line, I am using Array<String> instead of Array. You should do the same thing, using of course the proper generic type that the array holds.
Tested that code in playground and it prints the expected array.