Java Map String <ListString> looping - java

I'm trying to loop thu a map using the codes:
Map<String, List<String>> newMap = new HashMap<String, List<String>>();
List<String> newList = new ArrayList<String>();
Assign some default values on the Map
for ( int m = 1; m < attribteList.size(); m = m+2) {
String newName = newList.get(m);
newMap.put(newName , newList);
}
know I need to add values in the Map
for (another loop) {
String value1 = anyvalue;
String value2 = anyvalue;
Iterator it = pmMap.entrySet().iterator();
int cnt = 1;
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
if(value1.equalsIgnoreCase(pairs.getKey().toString())) {
for (List<String> list : pmMap.values()) {
int a = list.indexOf(list);
if (a == cnt) {
list.add(value2);
}
}
}
cnt++;
}
Problem is my loop doesn't work. I need to add value2 from the Map based from there position or value from the map
Like:
If Map String (15) is equal to value1 (15)
Find the Map Liststring with the value of 15 and place value2 inside.
Output data should be like this:
MAP: 15=[value2, 0, 0, 0] 16=[value2, 0, 0, 0, 0] 17=[value2, 0, ,0 ,0]
Anyone knows how to loop or search for the position or correct list?

First, I am guessing that this List<String> newList = new ArrayList<String>(); should be inside the loop you are updating your HashMap otherwise as #tobias_k mentioned you are inserting the same value to every key. I guess you don't want that.
You can use keySet() to get the key of your Map and loop in it:
Set<String> set = pmMap.keySet();
for(String key : set) {
ArrayList<String> list = null;
if(value1.equals(key)) {
list = pmMap.get(key);
list.add(value2);
pmMap.put(key, list);
}
I haven't checked the code but you got the idea.

Since you are assigning the same list to all values in the map you need not loop through the entry set. You could just get the value and do a replace all like Collections.replaceAll(list, value1, value2);
List<String> list = pmMap.get(value1);
if(list != null){
Collections.replaceAll(list, value1, value2);
}
A sample
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Test {
public static void main(String[] args) {
Map<String, List<String>> pmMap = new HashMap<String, List<String>>();
List<String> newList = new ArrayList<String>(){{ add("15"); add("16"); add("17"); add("18");}};
for (int m = 0; m < newList.size(); m++) {
String newName = newList.get(m);
pmMap.put(newName , newList);
}
System.out.println(pmMap);
String value1 = "15";
String value2 = "19";
List<String> list = pmMap.get(value1);
if(list != null){
Collections.replaceAll(list, value1, value2);
}
System.out.println(pmMap);
}
}

Related

Get all size of values in a HashMap<String,List<String,String>>

In my HashMap < String,List< String,String>> I saved keys (Name of a building) and values (Id´s from devices in this building).
I just want to get the size of values from each keys in my HashMap but the only size I get is from the first Key,Value pair...Here´s my code
Map<String, List<String>> moduleNamesWithAllParameters = new
HashMap<String, List<String>>();
List<String> parameters = new ArrayList<String>();
List<String> moduleNames = new ArrayList<String>();
Iterator it;
int start = 0, end = 0, mapKeys = 0;
parameters.add("kExmWoEM2HpMA4CT");
parameters.add("ILm1nApv06lDtqva");
parameters.add("gu00xoO5WPTv0SEr");
parameters.add("kX4FIg6c3C10msex");
parameters.add("xUcA4Y5rvqxlg8ju");
parameters.add("TYjydK6AyY7vwYSo");
parameters.add("#");
parameters.add("IDvHK1vXMiDEPxad");
parameters.add("ja0D3LH8ML0mQwZ0");
parameters.add("#");
parameters.add("tKgYRVvguvl3ByRc");
parameters.add("I95sFdAOoUTHjO7Y");
moduleNames.add("Building 1");
moduleNames.add("Building 2");
moduleNames.add("Building 3");
it = parameters.iterator();
for (int i = 0; i < moduleNames.size(); i++) {
do {
end++;
} while (it.hasNext() && !(it.next().equals("#")));
moduleNamesWithAllParameters.put(moduleNames.get(i), parameters.subList(start, end - 1));
start = end;
}
for (String key : moduleNamesWithAllParameters.keySet())
System.out.println(key + " = " + moduleNamesWithAllParameters.get(key));
Entry<String, List<String>> entry;
for (int i = 0; i < moduleNames.size(); i++) {
entry = moduleNamesWithAllParameters.entrySet().iterator().next();
mapKeys = entry.getValue().size();
System.out.println(mapKeys);
}
}
This line:
entry = moduleNamesWithAllParameters.entrySet().iterator().next();
Is constantly creating a new iterator over the entry set of the map and returning the first entry. So you will only ever see the first entry.
You can change the loop to loop over all entries like this:
for (Entry<String, List<String>> entry : moduleNamesWithAllParameters.entrySet()) {
mapKeys = entry.getValue().size();
System.out.println(mapKeys);
}
Assuming you're using Java8 or later:
moduleNamesWithAllParameters.entrySet().stream().forEach((entry) -> {
System.out.println(entry.getValue().size());
});
Replace your last loop with the following:
for (int i = 0; i < moduleNames.size(); i++) {
mapKeys = moduleNamesWithAllParameters.get(moduleNames.get(i)).size();
System.out.println(mapKeys);
}
Or a bit neater:
for(String key : moduleNamesWithAllParameters.keySet()) {
System.out.println(moduleNamesWithAllParameters.get(key).size());
}
Or even neater (Java 8+):
moduleNamesWithAllParameters.stream().forEach(entry ->
System.out.println(entry.getValue().getSize())
);
Or loop using valueSet (since you don't actually use the key):
for(List<String> value : moduleNamesWithAllParameters.valueSet()) {
System.out.println(value.size());
}
Or if you so fancy (Java 8+):
moduleNamesWithAllParameters.valueSet().stream().map(List::size).forEach(System.out::println);
Probleam is happend in this line:
entry = moduleNamesWithAllParameters.entrySet().iterator().next();
entrySet().iterator() is a new object each time it loops.
So you map size only is the first size.

I have to split array data ,make it key value pair and save in a Map

I have to split array data ,make it key value pair and save in a map,This is code using for split and save in subdate ,after that in data please clear this
Map<Integer, Map<String, String>> data = new HashMap<Integer, Map<String, String>>();
Map<String, String> subData = new HashMap<String, String>();
CLog.d("",""+fsplit.length);
for (int j = 1; j <=(fsplit.length/3); j++) {
CLog.d("fsplitsixe", "" + fsplit.length);
for (String test : fsplit) {
String s = test;
String[] parts = s.split("=");
if (parts.length == 2) {
subData.put(parts[0], parts[1]);
}
}
CLog.d("subsizetest",""+subData.size());
data.put(j, subData);
CLog.d(TAG, "MAKE_KEY_PAIR" + data);
}
My Array Data in fsplit is this :
0. url=http://www.krak.dk//53504900/s%C3%B8g.cs
1. datasource=ENIRODK_YELLOW_DATA
2. matchstring=hit-list
3. url=http://www.krak.dk/person/resultat/53504900
4. datasource=ENIRODK_WHITE_DATA
5. matchstring=hit-list
excepted output is:
MAKE_KEY_PAIR {
1 = {
matchstring = hit-list,
datasource = ENIRODK_YELLOW_DATA,
url = http://www.krak.dk//53504900/s%C3%B8g.cs
},
2 = {
matchstring = hit-list,
datasource = ENIRODK_WHITE_DATA,
url = http://www.krak.dk/person/resultat/53504900
}
}
But my output :
MAKE_KEY_PAIR {
1 = {
matchstring = hit-list,
datasource = ENIRODK_WHITE_DATA,
url = http://www.krak.dk/person/resultat/53504900
},
2 = {
matchstring = hit-list,
datasource = ENIRODK_WHITE_DATA,
url = http://www.krak.dk/person/resultat/53504900
}
}
Try below code:
Map<Integer, Map<String, String>> data = new LinkedHashMap<Integer, Map<String, String>>();
Map<String, String> subData;
for (int j= 0; j <fsplit.length;) {
subData = new HashMap<String, String>();
int i=0;
while(i<3){
String s = fsplit[j++];
String[] parts = s.split("=");
if (parts.length == 2) {
subData.put(parts[0], parts[1]);
}
i++;
}
data.put(j/3, subData);
}
subData Map has same data:
As you are using same subData Map, existing value is replace with new value, where key is same for both.
data Map has same data:
As you are iterating same fsplit array multiple time, always last 3 value is get added into data map.
Read the comments too
foreach loop Always pick the string content from beginning of the string(fsplit). After getting first result you are not updating fsplit.
fsplit is a Object of String Class which is immutable. So update the content of fsplit after getting your result
at each iteration
for (int j = 1; j <=(fsplit.length/3); j++) {
CLog.d("fsplitsixe", "" + fsplit.length);
for (String test : fsplit) {
/* this line always pick the string content from beginning of the string(fsplit).
After gettingfirst result you are not updating fsplit.
fsplit is a `Object` of `String` Class which is immutable.
So update the content of fsplit after getting your result
at each iteration */
String s = test;
String[] parts = s.split("=");
if (parts.length == 2) {
subData.put(parts[0], parts[1]);
}
}

How to take for loop output to separate array in Java?

I need to take following code output to separate array for use another calculation. In this example output is,
z count is= 1
y count is= 3
x count is= 2.
I need to take 1, 3, 2 to separate array. How I do it? I am new to Java.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class ForArrays {
public static void main(String[] args) {
ArrayList<String> name = new ArrayList<String>();
HashMap<String, Integer> termFreqMap = new HashMap<String, Integer>();
ArrayList<String> words = new ArrayList<String>();
HashMap<String, Integer> wordFreqMap = new HashMap<String, Integer>();
name.add("x");
name.add("y x");
name.add("y z y");
// count words
for (int j = 0; j < name.size(); j++) {
String tempname = name.get(j);
String[] result = tempname.split(" ");
for (String s : result) {
Integer twf = wordFreqMap.get(s);
if (twf == null)
wordFreqMap.put(s, new Integer(1));
else {
wordFreqMap.put(s, new Integer(++twf));
}
}
}
for (Map.Entry<String, Integer> entry : wordFreqMap.entrySet()) {
String tempWord = entry.getKey();
Integer wf = entry.getValue();
System.out.println(tempWord + " " + "count is= " + wf);
}
}
}
Create a int array with the size of the Hashmap so that both hashmap size and array size will be similar. And while iterating the Hashmap save the result in array.
The catch with this is hashmap doesn't have insertion order so the array will not be in insertion order.So you may not know the count is for what key.For that you can create one keys array and put the keys also there for one to one mapping of keys array and countarray.
int countArray[] = new int[wordFreqMap.size()];
int i=0;
for (Map.Entry<String, Integer> entry : wordFreqMap.entrySet()) {
String tempWord = entry.getKey();
Integer wf = entry.getValue();
System.out.println(tempWord + " " + "count is= " + wf);
countArray[i++] = wf;
}

Syncronized sorting between two ArrayLists

I have two ArrayLists.
The first contains a group of words with capitalization and
punctuation.
The other contains this same group of words, but with the
capitalization and punctuation removed.
.
ArrayList1 ..... ArrayList2
MURDER! ........ murder
It's ........... its
Hello .......... hello
Yes-Man ........ yesman
ON ............. on
The second array has all the words alphabetized and all the letters in each word alphabetized. It looks something like this:
aemnsy
demrru
ehllo
ist
no
I want to make it so that when I arrange the words in ArrayList two into alphabetical order, all the words from ArrayList one follow suite:
ArrayList1 ..... ArrayList2
Yes-Man ........ aemnsy
MURDER! ........ demrru
Hello .......... ehllo
It's ........... ist
ON ............. no
I tried to make a loop with a for statement or two, but it ended up not working and became very long. How do I do this? How do I do this efficiently?
Here is a function to sort multiple lists based on a single 'key' list. The lists do not need to be the same type, here the key list is type String and it's used to sort a String, Integer, and Double list (Ideone Example):
List<String> key = Arrays.asList("demrru", "ist", "ehllo", "aemnsy", "no");
List<String> list1 = Arrays.asList("MURDER!","It's", "Hello","Yes-Man", "ON");
List<Integer> list2 = Arrays.asList(2, 4, 3, 1, 5); // Also use Integer type
List<Double> list3 = Arrays.asList(0.2, 0.4, 0.3, 0.1, 0.5); // or Double type
// Sort all lists (excluding the key)
keySort(key, list1, list2, list3);
// Sort all lists (including the key)
keySort(key, key, list1, list2, list3);
Output:
// Sorted by key:
[Yes-Man, MURDER!, Hello, It's, ON]
[aemnsy, demrru, ehllo, ist, no]
[1, 2, 3, 4, 5]
[0.1, 0.2, 0.3, 0.4, 0.5]
Sort Function
An Ideone Example can be found here which includes validation of parameters and a test case.
public static <T extends Comparable<T>> void keySort(
final List<T> key, List<?>... lists){
// Create a List of indices
List<Integer> indices = new ArrayList<Integer>();
for(int i = 0; i < key.size(); i++)
indices.add(i);
// Sort the indices list based on the key
Collections.sort(indices, new Comparator<Integer>(){
#Override public int compare(Integer i, Integer j) {
return key.get(i).compareTo(key.get(j));
}
});
// Create a mapping that allows sorting of the List by N swaps.
Map<Integer,Integer> swapMap = new HashMap<Integer, Integer>(indices.size());
// Only swaps can be used b/c we cannot create a new List of type <?>
for(int i = 0; i < indices.size(); i++){
int k = indices.get(i);
while(swapMap.containsKey(k))
k = swapMap.get(k);
swapMap.put(i, k);
}
// for each list, swap elements to sort according to key list
for(Map.Entry<Integer, Integer> e : swapMap.entrySet())
for(List<?> list : lists)
Collections.swap(list, e.getKey(), e.getValue());
}
First Way - I use map whose key is from arrayList2 and value is from arrayList1. Putting data to map is up to you. After sorting arrayList2, I get its value from map.
List<String> arrList1 = new ArrayList<String>();
arrList1.add("MURDER!");
arrList1.add("It's");
arrList1.add("Hello");
arrList1.add("Yes-Man");
arrList1.add("ON");
List<String> arrList2 = new ArrayList<String>();
arrList2.add("demrru");
arrList2.add("aemnsy");
arrList2.add("ist");
arrList2.add("ehllo");
arrList2.add("no");
Map<String, String> map1 = new HashMap<String, String>();
map1.put("aemnsy", "Yes-Man");
map1.put("demrru", "MURDER!");
map1.put("ehllo", "Hello");
map1.put("ist", "It's");
map1.put("no", "ON");
Collections.sort(arrList2);
for (String s : arrList2){
System.out.println(s + "..........." + map1.get(s));
}
Second Way - Another way is you can use only TreeMap which is already sorted instead of two ArrayList.
Map<String, String> map2 = new TreeMap<String, String>();
map2.put("ehllo", "Hello");
map2.put("aemnsy", "Yes-Man");
map2.put("demrru", "MURDER!");
map2.put("no", "ON");
map2.put("ist", "It's");
for (Map.Entry<String, String> entry : map2.entrySet())
{
System.out.println(entry.getKey() + "/" + entry.getValue());
}
Third way - only using 2 ArrayList, but we have to write sorting method by our own. Have you notice that your 2 ArrayList elements such as aemnsy from arrayList2 and Yes-Man from arrayList1 have same index? I use that point.
selectionSort1(arrList2, arrList1);
for(int i = 0; i < arrList1.size(); i++){
System.out.println(arrList2.get(i) + "---" + arrList1.get(i));
}
public static void selectionSort1(List<String> x, List<String> y) {
for (int i=0; i<x.size()-1; i++) {
for (int j=i+1; j<x.size(); j++) {
if (x.get(i).compareTo(x.get(j)) > 0) {
//... Exchange elements in first array
String temp = x.get(i);
x.set(i, x.get(j));
x.set(j, temp);
//... Exchange elements in second array
temp = y.get(i);
y.set(i, y.get(j));
y.set(j, temp);
}
}
}
}
A Quick Answer.
public class MapAlph {
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<String, String>();
String txt = "Murde!r!";
ArrayList<Character> alph = new ArrayList<Character>();
for (int i = 0; i < txt.length(); i++)
if (Character.isLetter(txt.charAt(i)))
alph.add(txt.charAt(i));
Collections.sort(alph);
Collections.reverse(alph);
String val = "";
for (Character c : alph)
val += c;
map.put(txt, val);
System.out.print(txt + " ........ " + map.get(txt));
}
}
You can make use of TreeMap, if you wish.
Map<String, String> sortedMap = new TreeMap<String, String>();
sortedMap.put("demrru", "MURDER!");
sortedMap.put("ist", "It's");
sortedMap.put("aemnsy", "Yes-Man");
sortedMap.put("ehllo", "Hello");
sortedMap.put("no", "ON");
You can try this:
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class SortService {
public static void main(String[] args) {
Map<String, String> originalMap = new HashMap<String, String>();
originalMap.put("aemnsy", "Yes-Man");
originalMap.put("demrru", "MURDER!");
originalMap.put("ehllo", "Hello");
originalMap.put("ist", "It's");
originalMap.put("no", "ON");
Map<String, String> sortedMap = new TreeMap<String, String>(originalMap);
System.out.println(sortedMap);
}
}
output:
{aemnsy=Yes-Man, demrru=MURDER!, ehllo=Hello, ist=It's, no=ON}

How to convert a HashMap of Objects into an ArrayList of Strings

I have a HashMap like so:
Hashmap<String, Object> map = new Hashmap<String, Object>();
map.put(1, {id_student:"1;2;3"});
map.put(2, {id_student:"4;5"});
I want to get the values and put it in an ArrayList like:
array = [0] - 1
[1] - 2
[2] - 3
[3] - 4
[4] - 5
what I tried to do:
private Set<String> checked = new TreeSet<String>();
String idsAlunos = "";
for (Iterator<Map.Entry<String, GPSEscolas>> it = aMap.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<String, GPSEscolas> entry = it.next();
String id_escola = entry.getKey();
String ids_aluno = entry.getValue().getAlunos();
idsAlunos += ";" + ids_aluno;
checked.add(idsAlunos.substring(1));
}
but I'm getting this result from above code: [4, 4;1;2;3, 4;5, 4;5;1;2;3]
You have to do it in steps:
Iterate over the Map keys or get the Map values as Collection and iterate over that.
Parse each value's comma separated value String into individual tokens and add them to the List or Set of values you want.
Sort the List of values once you have it.
Use a Set if you'd rather not have duplicates.
Looks like JSON. Are you using JSONSimple? Perhaps you should be.
Here's an example.
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* MapToArrayExample
* User: mduffy
* Date: 6/24/2015
* Time: 3:17 PM
* #link http://stackoverflow.com/questions/31034737/how-to-convert-a-hashmap-of-objects-into-an-arraylist-of-strings/31034794?noredirect=1#comment50094533_31034794
*/
public class MapToArrayExample {
public static void main(String[] args) {
Map<Integer, String> data = new HashMap<Integer, String>() {{
put(1, "3, 2, 3, 3, 1");
put(2, "4, 5, 5, 6, 7");
}};
List<String> result = parseMapOfJson(data);
System.out.println(result);
}
public static List<String> parseMapOfJson(Map<Integer, String> map) {
List<String> values = new ArrayList<String>();
for (Integer key : map.keySet()) {
String csv = map.get(key);
String [] tokens = csv.split(",");
for (String token : tokens) {
values.add(token.trim());
}
}
Collections.sort(values);
return values;
}
}
Ok, I got it, it is like this:
idsAlunos = "";
for (Iterator<Map.Entry<String, GPSEscolas>> it = aMap.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<String, GPSEscolas> entry = it.next();
String id_escola = entry.getKey();
String ids_aluno = entry.getValue().getAlunos();
idsAlunos += ";" + ids_aluno;
String[] array = idsAlunos.substring(1).split(";");
list = new ArrayList<String>(Arrays.asList(array));
}
System.out.println(list);
and that gives me what I want, which is: [4,5,1,2,3]
Try this:
HashMap<String, String> map = new HashMap<String, String>();
map.put("1", "1;2;3");
map.put("2", "4;5");
Set<String> checked = new TreeSet<String>();
for (Iterator i = map.entrySet().iterator(); i.hasNext();) {
Map.Entry<String, String> e = (Map.Entry<String, String>) i.next();
checked.addAll(Arrays.asList(e.getValue().split("\\s*;\\s*")));
}
System.out.println(checked);

Categories

Resources