So if i have the following:
TreeMap<Integer, TreeSet<String>> returnMap = new TreeMap<Integer, TreeSet<String>>();
How do I create an iterator for the treeset inside of the map?
I tried the following:
Iterator<String> mapItr = returnMap.values();
If you don't care about order...
final TreeMap<Integer, TreeSet<String>> returnMap = new TreeMap<Integer, TreeSet<String>>();
final List<String> strings = new ArrayList();
for (final TreeSet<String> treeSet : returnMap.values()) {
strings.addAll(treeSet);
}
final Iterator<String> mapItr = strings.iterator();
In Java 8, using streams, it could be:
final Iterator<String> mapItr = returnMap
.values()
.stream()
.flatMap(Set::stream)
.collect(Collectors.toList())
.iterator();
If you do care about order, you will need to go through your TreeSet instances in whatever order you want.
Related
I have a map with 10 000 keys and it looks like this:
Map<String, List<Integer>>. I want to make a list of Map<String, List<Integer>> which will contains 50 submaps X 200 elements.
This is the code:
Map<String, List<Integer>> map = new HashMap<>();
for (int i = 0; i < 10000; i++) {
map.put(String.valueOf(i),new ArrayList<>(Arrays.asList(new Random().nextInt(100),new Random().nextInt(200),new Random().nextInt(300)
,new Random().nextInt(400))));
}
List<Map<String, List<Integer>>> list = new ArrayList<>();
Map<String,List<Integer>> submap = new TreeMap<>();
List<Map<String, List<Integer>>> sublist = new ArrayList<>();
for (Map.Entry<String, List<Integer>> stringListEntry : map.entrySet()) {
submap.put(stringListEntry.getKey(),stringListEntry.getValue());
if (submap.size() == 200){
sublist.add(submap);
list.addAll(sublist);
sublist.clear();
submap.clear();
}
}
System.out.println(list);
but the list by the end is empty.
Why does this happen?
You need to generate a new sub-Map when the desired size is reached, instead of cleaning the same sub-Map and placing it into the resulting list multiple times.
List<NavigableMap<String, List<Integer>>> list = new ArrayList<>();
NavigableMap<String, List<Integer>> submap = new TreeMap<>();
final int limit = 200;
for (Map.Entry<String, List<Integer>> entry : map.entrySet()) {
submap.put(entry.getKey(), entry.getValue());
if (submap.size() == limit) {
list.add(submap);
submap = new TreeMap<>();
}
}
Sidenote: it's more beneficial to use NavigableMap interface while working with a TreeMap because it offers many methods firtKey(), higherKey(), etc. that are not defined in the Map interface.
Issue
I'm trying to sort a map Map>
which the map key set contain the order 1 2 3 4 ext ...
Code
The file which I'm retrieving data
filter.properties
1=gwtCacheControlFilter:com.palmyra.arch.presentation.port.server.GWTCacheControlFilter:true:/*:null:presentation
public Map<String, List<String>> initiateMapOfFilters() throws IOException {
Map<String, List<String>> filterMap = new HashMap<>();
Properties properties = new Properties();
properties.load(FilterFileStream);
for (Entry<Object, Object> filterFromFile : properties.entrySet()) {
String filterValue = filterFromFile.getValue().toString();
String[] split = filterValue.split(":");
ArrayList<String> list = new ArrayList<>();
for (String s : split) {
list.add(s);
}
//-------sort the list with order
filterMap.put(split[filterNameIndex], list);
}
// Map<String, String> treeMap = new TreeMap<String, String>((Comparator<? super String>) filterMap); comment
return filterMap;
}
What I've tried
I want to return a map ordered by the key I tried:
Map<String, String> treeMap = new TreeMap<String, String>((Comparator<? super String>) filterMap);
Thank you for any suggestion.
You have to use a comparator to make it work! Like this :
Map<Integer,String> unsortedMap = new Hashmap<Integer,String>();
Map<Integer,String> treeMap = new TreeMap<Integer,String>(
new Comparator<Integer>() {
#Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);//sort in descending order
}
});
Consider the below code. With java 8 you can use the Comparator.comparing method and get it done quite quickly.
TreeMap<String, List<String>> treeMap = new TreeMap<>(Comparator.comparing(t -> Integer.valueOf(t)));
treeMap.put("5", Arrays.asList(new String[] {"data1", "data2", "data3"}));
treeMap.put("3", Arrays.asList(new String[] {"data4", "data5", "data6"}));
treeMap.put("1", Arrays.asList(new String[] {"data7", "data8", "data9"}));
treeMap.put("4", Arrays.asList(new String[] {"data10", "data11", "data12"}));
treeMap.
forEach((k,v) -> System.out.println(k + "=="+v));
Output is sorted on basis of keys:
1==[data7, data8, data9]
3==[data4, data5, data6]
4==[data10, data11, data12]
5==[data1, data2, data3]
can I get a Hashmap which key orderly except use LinkeHashmap?
Map<String,String> myMapTmp = XXDao().getXXX();
Map<String,String> myMap = new LinkedHashMap<String,String>();
List<String> keyList = new ArrayList<String>();
Iterator<String> it =myMapTmp.keySet().iterator();
while(it.hasNext()){
keyList.add(it.next());
}
Collections.sort(keyList);
Iterator<String> it2 = keyList.iterator();
while(it2.hasNext()){
String key = it2.next();
myMap.put(key, myMapTmp.get(key));
}
You can use TreeMap with mappings of HashMap
Map<String,String> myMapTmp = XXDao().getXXX();
// TreeMap keeps all entries in sorted order
TreeMap<String, String> sortedMap = new TreeMap<>(myMapTmp);
Set<Entry<String, String>> mappings = sortedMap.entrySet();
System.out.println("HashMap after sorting by keys in ascending order ");
for(Entry<String, String> mapping : mappings){
System.out.println(mapping.getKey() + " ==> " + mapping.getValue());
}
You can create a treeMap from the existing map so the treeMap will have all the entries sorted.
TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>();
treeMap.putAll(myMapTmp);
Simply use LinkedHashMap. it will give you desired result.
I've a SortedMap<String, String> containing key:ID & value:Name.
Now I want to rearrange the elements of this Map in random fashion & store them in separate map.
// Get a random entry from the SortedMap.
String[] keyArr = student.keySet().toArray();
String key = keyArr[new Random().nextInt(keyArr.length)];
// Use a separate List<String> to store which key has been selected, so that they are not re-selected
But above method does not sound very efficient.
Please suggest.
Thank You
You would need to copy the entrySet into a List and shuffle it. This would give you the elements in a random order.
Now you can push those elements to a new LinkedHashMap - to preserve the random order. Something like the following:
final Map<String, Object> m = new TreeMap<>();
m.put("A", 1);
m.put("B", 1);
m.put("C", 1);
m.put("D", 1);
m.put("E", 1);
m.put("F", 1);
m.put("G", 1);
final List<Map.Entry<String, Object>> e = new ArrayList<>(m.entrySet());
Collections.shuffle(e);
final Map<String, Object> r = new LinkedHashMap<>();
for (Map.Entry<String, Object> entry : e) {
r.put(entry.getKey(), entry.getValue());
}
I'm not sure that I got your question, but you should be able to do something like
Map<String, String> result = new LinkedHashMap<>();
List keys = new ArrayList(map.keySet());
Collections.shuffle(keys);
for (Object o : keys) {
// Access keys/values in a random order
result.put(o, map.get(o));
}
In Java, how does one get the values of a HashMap returned as a List?
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put (1, "Mark");
map.put (2, "Tarryn");
List<String> list = new ArrayList<String>(map.values());
for (String s : list) {
System.out.println(s);
}
Assuming you have:
HashMap<Key, Value> map; // Assigned or populated somehow.
For a list of values:
List<Value> values = new ArrayList<Value>(map.values());
For a list of keys:
List<Key> keys = new ArrayList<Key>(map.keySet());
Note that the order of the keys and values will be unreliable with a HashMap; use a LinkedHashMap if you need to preserve one-to-one correspondence of key and value positions in their respective lists.
Basically you should not mess the question with answer, because it is confusing.
Then you could specify what convert mean and pick one of this solution
List<Integer> keyList = Collections.list(Collections.enumeration(map.keySet()));
List<String> valueList = Collections.list(Collections.enumeration(map.values()));
Collection Interface has 3 views
keySet
values
entrySet
Other have answered to to convert Hashmap into two lists of key and value. Its perfectly correct
My addition: How to convert "key-value pair" (aka entrySet)into list.
Map m=new HashMap();
m.put(3, "dev2");
m.put(4, "dev3");
List<Entry> entryList = new ArrayList<Entry>(m.entrySet());
for (Entry s : entryList) {
System.out.println(s);
}
ArrayList has this constructor.
Solution using Java 8 and Stream Api:
private static <K, V> List<V> createListFromMapEntries (Map<K, V> map){
return map.values().stream().collect(Collectors.toList());
}
Usage:
public static void main (String[] args)
{
Map<Integer, String> map = new HashMap<>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
List<String> result = createListFromMapEntries(map);
result.forEach(System.out :: println);
}
If you only want it to iterate over your HashMap, no need for a list:
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put (1, "Mark");
map.put (2, "Tarryn");
for (String s : map.values()) {
System.out.println(s);
}
Of course, if you want to modify your map structurally (i.e. more than only changing the value for an existing key) while iterating, then you better use the "copy to ArrayList" method, since otherwise you'll get a ConcurrentModificationException. Or export as an array:
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put (1, "Mark");
map.put (2, "Tarryn");
for (String s : map.values().toArray(new String[]{})) {
System.out.println(s);
}
If you wanna maintain the same order in your list, say:
your Map looks like:
map.put(1, "msg1")
map.put(2, "msg2")
map.put(3, "msg3")
and you want your list looks like
["msg1", "msg2", "msg3"] // same order as the map
you will have to iterate through the Map:
// sort your map based on key, otherwise you will get IndexOutofBoundException
Map<String, String> treeMap = new TreeMap<String, String>(map)
List<String> list = new List<String>();
for (treeMap.Entry<Integer, String> entry : treeMap.entrySet()) {
list.add(entry.getKey(), entry.getValue());
}
I use usually map.values() to get values, then convert them to list
let say you have this Hashmap:
HashMap<String, Integer> map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);
You can get values from the map, then convert them to a list in one code line like that:
List<Integer> values = map.values().stream()
.collect(Collectors.toList());