Removing item from a list inside hashmap - java

I have an List<String> in a HashMap as value. The key is a String. When I loop through the HashMap and remove items from the list of a particular key it updates the lists mapped to all the keys in the map.
The code is below
public class ListClass {
public static void main(String[] args) {
ListClass lc = new ListClass();
for(Map.Entry<String, List<String>> entry : lc.postProcessList().entrySet()) {
System.out.println("Date : "+entry.getKey());
List<String> data = entry.getValue();
for (int i = 0; i < data.size(); i++) {
System.out.println(" Value : "+data.get(i));
}
}
}
private Map<String,List<String>> postProcessList() {
Map<String,List<String>> map = new HashMap<String, List<String>>();
populateMap(map);
for(Map.Entry<String, List<String>> entry : map.entrySet()) {
String dateKey = entry.getKey();
System.out.println("Date key : "+dateKey);
List<String> data = entry.getValue();
System.out.println("List before modification : "+data);
for (int i = 0; i < data.size(); i++) {
String dateNoTime = data.get(i).split(" ")[0];
if(!dateNoTime.equalsIgnoreCase(dateKey)) {
System.out.println("Removing : "+data.get(i));
data.remove(i);
}
}
System.out.println("List after modification: "+data+"\n\n");
}
return map;
}
private Map<String,List<String>> populateMap(Map<String,List<String>> map) {
List<String> list = new ArrayList<String>();
list.add("2015-01-13 09:30:00");
list.add("2015-01-12 05:45:10");
list.add("2015-01-13 06:22:12");
list.add("2015-01-12 01:52:40");
list.add("2015-01-12 02:23:45");
map.put("2015-01-12", list);
map.put("2015-01-13", list);
return map;
}
}
In the above code, the Map has key which is a string and holds date values. List, which is the value of the map, holds date and time.
First key is "2015-01-12" and I'm trying to remove the items in the list that are not "2015-01-12". Now the list in both the keys get's updated. Why is that so?

You are adding the same list instance to the map against both keys. Therefore when you retrieve it using key "2015-01-12" and edit it, you'll see the changes in the entire map.
You need to clone the list using something like list.clone() or new ArrayList<String>(list) before you add it to each key.
e.g.
ArrayList<String> list = new ArrayList<String>();
list.add("2015-01-13 09:30:00");
list.add("2015-01-12 05:45:10");
list.add("2015-01-13 06:22:12");
list.add("2015-01-12 01:52:40");
list.add("2015-01-12 02:23:45");
map.put("2015-01-12", (List<String>)list.clone());
map.put("2015-01-13", (List<String>)list.clone());

Related

How to sort map or which traversal approach i need to follow?

i just want to get a Sorted map my code is like :
public class SubString {public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("string2");
list.add("STR_str2");
list.add("STR_str3");
getSequesce("STR_str1", list);
List<String> list1 = new ArrayList<>();
list1.add("STR_xyz");
list1.add("STR_ABC");
getSequesce("STR_str2", list1);
List<String> list3 = new ArrayList<>();
list3.add("Anukul");
list3.add("mittal");
getSequesce("STR_str3", list3);
List<String> list4 = new ArrayList<>();
list4.add("Test");
list4.add("STR_XYZ");
getSequesce("STR_ABC", list4);
List<String> list5 = new ArrayList<>();
list5.add("val");
list5.add("var");
getSequesce("STR_XYZ", list5);
List<String> list6 = new ArrayList<>();
list6.add("val6");
list6.add("valtest");
getSequesce("STR_free", list6);
List<String> list7 = new ArrayList<>();
list7.add("val6");
list7.add("STR_free");
getSequesce("STR_7", list7);
}private static void getSequesce(String string, List<String> list) {
Map<String, List<String>> map = new HashMap<>();
Map<String, List<String>> sortedMap = new TreeMap<>();
map.put(string, list);
for (Map.Entry<String, List<String> > itrMap : map.entrySet() ) {
}
}}
In my fist call of getSequence method i have put a string "STR_str1" and a list.
i just want to add this into a map where key is STR_str1 and its value is list.
but my problem is i have to put STR_str2 ,and STR_str3 as key in map before STR_str1. similarly i have to put STR_ABC and STR_XYZ before STR_str2.
i just want a sortedMap from function getSequesce so that i get output like
STR_free,list6
"STR_7", list7
STR_XYZ,list5
STR_ABC,list4
STR_str3,list3
"STR_str2", list1
"STR_str1", list
if value of list start with STR_ then this STR_ must already avail in map.
position of "STR_free", list6 "STR_XYZ", list5 "STR_str3", list3 can be anywhere because they don't contain any dependency.
please help me to suggest what approach i can follow. i have data that will not create cyclic problem.
Thanks.
Map by definition is not sorted (The same as set) so the traversal order is not guaranteed. However there is a interface SortedMap and its implementations (Such as TreeMap). In this case your keys must implement equals() and hashcode() in a meaningful way or implement Comparable interface. In your case you use Strings as keys and String implements comparable. So you can use SortedMap
Thank you for help guys code i was looking for is
private static Map<String, List<String>> map = new LinkedHashMap<String, List<String>>();
private static List<String> nonDependentList = new ArrayList<String>();
private static Map<String, List<String>> dependentMap = new ConcurrentHashMap<String, List<String>>();
public static void main(String[] args) {
List<String> list1 = new ArrayList<>();
list1.add("string2");
list1.add("STR_str2");
list1.add("STR_str3");
addRecord("STR_str1", list1);
List<String> list2 = new ArrayList<>();
list2.add("STR_xyz");
list2.add("STR_ABC");
addRecord("STR_str2", list2);
List<String> list3 = new ArrayList<>();
list3.add("Anukul");
list3.add("mittal");
addRecord("STR_str3", list3);
List<String> list4 = new ArrayList<>();
list4.add("Test");
list4.add("STR_XYZ");
addRecord("STR_ABC", list4);
List<String> list5 = new ArrayList<>();
list5.add("val");
list5.add("var");
addRecord("STR_XYZ", list5);
List<String> list6 = new ArrayList<>();
list6.add("val6");
list6.add("valtest");
addRecord("STR_free", list6);
List<String> list7 = new ArrayList<>();
list7.add("val6");
list7.add("STR_free");
addRecord("STR_7", list7);
Map<String, List<String>> processedMap = proceedAndFetchRecords();
System.out.println("Final result");
for (Entry<String, List<String>> entry : processedMap.entrySet()) {
System.out.println("Key : " + entry.getKey() + " || Values : " + entry.getValue());
}
}
private static Map<String, List<String>> proceedAndFetchRecords() {
for (Entry<String, List<String>> entry : map.entrySet()) {
boolean flag = isNotDependent(entry.getValue());
// System.out.println("Key : " + entry.getKey() + " isNotDependent :
// " + flag);
if (flag) {
nonDependentList.add(entry.getKey());
} else {
List<String> list = getOnlyDependentList(entry.getValue());
dependentMap.put(entry.getKey(), list);
}
}
// showDependentMap();
refreshDependentMap();
// Final result
Map<String, List<String>> processedMap = addResultsInMap();
return processedMap;
}
private static void refreshDependentMap() {
for (Entry<String, List<String>> entry : dependentMap.entrySet()) {
List<String> list = entry.getValue();
list.removeAll(nonDependentList);
boolean flag = isNotDependent(list);
if (flag) {
nonDependentList.add(entry.getKey());
dependentMap.remove(entry.getKey());
refreshDependentMap();
} else {
continue;
}
}
}
private static Map<String, List<String>> addResultsInMap() {
Map<String, List<String>> processedMap = new LinkedHashMap<String, List<String>>();
for (String key : nonDependentList) {
processedMap.put(key, map.get(key));
}
for (Entry<String, List<String>> entry : dependentMap.entrySet()) {
processedMap.put(entry.getKey(), map.get(entry.getKey()));
}
return processedMap;
}
private static boolean isNotDependent(List<String> list) {
int count = 0;
for (String string : list) {
if (!string.startsWith("STR_")) {
++count;
}
}
if (list.size() == count) {
return true;
}
return false;
}
private static void addRecord(String structureName, List<String> list) {
map.put(structureName, list);
}
private static List<String> getOnlyDependentList(List<String> list) {
List<String> list1 = new ArrayList<>();
for (String string : list) {
if (string.startsWith("STR_")) {
list1.add(string);
}
}
return list1;
}}

How to reverse a HashMap?

I need to reverse the order of what the below method returns. For example if it
returns:
1=ball, 2=save, 3=take 4=till
I want to reverse and return:
1=till, 2=take, 3=save, 4=ball
My method is:
public Map<Integer, String> returnMapOfValues(ArrayList<String> wordsList) {
int getFrequencyValue = 0;
Set<String> uniqueSetWords = new HashSet<String>(wordsList);
for (String temp : uniqueSetWords) {
getFrequencyValue = Collections.frequency(wordsList, temp);
//prints the Collection of words and they frequency, For testing only
//System.out.println(temp + ":" + Collections.frequency(wordsList,
//temp));
map.put(getFrequencyValue, temp);
getFrequencyValue = 0;
}
return map;
}
Please check if the below code I've written is useful for you as a reference:
public void reverseMap()
{
NavigableMap<Integer,String> map = new TreeMap<Integer,String>();
LinkedHashMap<Integer,String> reverseMap = new LinkedHashMap<Integer,String>();
map.put(1,"Apple");
map.put(2,"Ball");
map.put(3,"Cat");
NavigableSet<Integer> keySet = map.navigableKeySet();
Iterator<Integer> iterator = keySet.descendingIterator();
Integer i;
while(iterator.hasNext())
{
i = iterator.next();
reverseMap.put(i,map.get(i));
}
System.out.println(reverseMap);
}
//map to arrange inizialized
LinkedHashMap<String,object> mta;
//transforms into arrayList hashmap keys and values
ArrayList<Object> valuesTMP=new ArrayList<Object>(mta.values());
ArrayList<String> keysTMP;
keysTMP=new ArrayList<String>(mta.keySet());
//reverse
Collections.reverse(valuesTMP);
Collections.reverse(keysTMP);
LinkedHashMap <String,Object> mtarranged=new LinkedHashMap<String, Object>();
int index=0;
for( String key : keysTMP){
mtarranged.put(key,valuesTMP.get(index));
index++;
}
To answer this question, we need to know how you're iterating the Map since Maps don't have entry order. However, you may try using a TreeMap which has the method descendingMap:
public Map<Integer, String> returnMapOfValues(ArrayList<String> wordsList) {
TreeMap<Integer, String> map = new TreeMap<Integer, String>();
int getFrequencyValue = 0;
Set<String> uniqueSetWords = new HashSet<String>(wordsList);
for (String temp : uniqueSetWords) {
getFrequencyValue = Collections.frequency(wordsList, temp);
//prints the Collection of words and they frequency, For testing only
//System.out.println(temp + ":" + Collections.frequency(wordsList,
//temp));
map.put(getFrequencyValue, temp);
getFrequencyValue = 0;
}
return map.descendingMap();
}
Edit: From your comment, your intent is more clear. A TreeMap will help you with your goal because it is a Map ordered by the natural order of the keys.
I've made some changes to the code. Please check if this is OK for you now.
public void reverseMap()
{
NavigableMap<Integer,String> map = new TreeMap<Integer,String>();
LinkedHashMap<Integer,String> reverseMap = new LinkedHashMap<Integer,String>();
map.put(1,"Apple");
map.put(2,"Ball");
map.put(3,"Cat");
NavigableSet<Integer> keySet = map.navigableKeySet();
Iterator<Integer> forwardIterator = keySet.iterator();
Iterator<Integer> reverseIterator = keySet.descendingIterator();
Integer i;
Integer j;
while(forwardIterator.hasNext())
{
i = forwardIterator.next();
j = reverseIterator.next();
reverseMap.put(i,map.get(j));
}
System.out.println(reverseMap);
}
Please find the below code and Let me know Which is suitable for you ...
int iterationValue = 0;
List<String> stringList = new LinkedList<String>();
stringList.add("ball");
stringList.add("save");
stringList.add("tick");
Map<Integer, String> map = new HashMap<Integer, String>();
for (String temp : stringList) {
map.put(iterationValue++, temp);
}
// Input MAP
System.out.println(map); // {0=ball, 1=save, 2=tick}
Collections.reverse(stringList);
iterationValue = 0;
for (String temp : stringList) {
map.put(iterationValue++, temp);
}
// Output MAP
System.out.println(map); // {0=tick, 1=save, 2=ball}

Storing and Retrieving ArrayList values from hashmap

I have a hashmap of the following type
HashMap<String,ArrayList<Integer>> map=new HashMap<String,ArrayList<Integer>>();
The values stored are like this :
mango | 0,4,8,9,12
apple | 2,3
grapes| 1,7
peach | 5,6,11
I want to store as well as fetch those Integers using Iterator or any other way with minimum lines of code.How can I do it?
EDIT 1
The numbers are added at random (not together) as key is matched to the appropriate line.
EDIT 2
How can I point to the arraylist while adding ?
I am getting error while adding a new number 18 in the line map.put(string,number);
Our variable:
Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();
To store:
map.put("mango", new ArrayList<Integer>(Arrays.asList(0, 4, 8, 9, 12)));
To add numbers one and one, you can do something like this:
String key = "mango";
int number = 42;
if (map.get(key) == null) {
map.put(key, new ArrayList<Integer>());
}
map.get(key).add(number);
In Java 8 you can use putIfAbsent to add the list if it did not exist already:
map.putIfAbsent(key, new ArrayList<Integer>());
map.get(key).add(number);
Use the map.entrySet() method to iterate on:
for (Entry<String, List<Integer>> ee : map.entrySet()) {
String key = ee.getKey();
List<Integer> values = ee.getValue();
// TODO: Do something.
}
The modern way (as of 2020) to add entries to a multimap (a map of lists) in Java is:
map.computeIfAbsent("apple", k -> new ArrayList<>()).add(2);
map.computeIfAbsent("apple", k -> new ArrayList<>()).add(3);
According to Map.computeIfAbsent docs:
If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.
Returns:
the current (existing or computed) value associated with the specified key, or null if the computed value is null
The most idiomatic way to iterate a map of lists is using Map.forEach and Iterable.forEach:
map.forEach((k, l) -> l.forEach(v -> /* use k and v here */));
Or, as shown in other answers, a traditional for loop:
for (Map.Entry<String, List<Integer>> e : map.entrySet()) {
String k = e.getKey();
for (Integer v : e.getValue()) {
/* use k and v here */
}
}
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
if(pairs.getKey().equals("mango"))
{
map.put(pairs.getKey(), pairs.getValue().add(18));
}
else if(!map.containsKey("mango"))
{
List<Integer> ints = new ArrayList<Integer>();
ints.add(18);
map.put("mango",ints);
}
it.remove(); // avoids a ConcurrentModificationException
}
EDIT:
So inside the while try this:
map.put(pairs.getKey(), pairs.getValue().add(number))
You are getting the error because you are trying to put an integer to the values, whereas it is expected an ArrayList.
EDIT 2:
Then put the following inside your while loop:
if(pairs.getKey().equals("mango"))
{
map.put(pairs.getKey(), pairs.getValue().add(18));
}
else if(!map.containsKey("mango"))
{
List<Integer> ints = new ArrayList<Integer>();
ints.add(18);
map.put("mango",ints);
}
EDIT 3:
By reading your requirements, I come to think you may not need a loop. You may want to only check if the map contains the key mango, and if it does add 18, else create a new entry in the map with key mango and value 18.
So all you may need is the following, without the loop:
if(map.containsKey("mango"))
{
map.put("mango", map.get("mango).add(18));
}
else
{
List<Integer> ints = new ArrayList<Integer>();
ints.add(18);
map.put("mango", ints);
}
You can use like this(Though the random number generator logic is not upto the mark)
public class WorkSheet {
HashMap<String,ArrayList<Integer>> map = new HashMap<String,ArrayList<Integer>>();
public static void main(String args[]) {
WorkSheet test = new WorkSheet();
test.inputData("mango", 5);
test.inputData("apple", 2);
test.inputData("grapes", 2);
test.inputData("peach", 3);
test.displayData();
}
public void displayData(){
for (Entry<String, ArrayList<Integer>> entry : map.entrySet()) {
System.out.print(entry.getKey()+" | ");
for(int fruitNo : entry.getValue()){
System.out.print(fruitNo+" ");
}
System.out.println();
}
}
public void inputData(String name ,int number) {
Random rndData = new Random();
ArrayList<Integer> fruit = new ArrayList<Integer>();
for(int i=0 ; i<number ; i++){
fruit.add(rndData.nextInt(10));
}
map.put(name, fruit);
}
}
OUTPUT
grapes | 7 5
apple | 9 5
peach | 5 5 8
mango | 4 7 1 5 5
You could try using MultiMap instead of HashMap
Initialising it will require fewer lines of codes. Adding and retrieving the values will also make it shorter.
Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();
would become:
Multimap<String, Integer> multiMap = ArrayListMultimap.create();
You can check this link: http://java.dzone.com/articles/hashmap-%E2%80%93-single-key-and
Method1 : Use putIfAbsent
Map<String, List<Integer>> map = new HashMap();
map.putIfAbsent("mango",new ArrayList<>());
map.get("mango").add(5);
Method 2: Check key present in Map
Map<String, List<Integer>> map = new HashMap();
if(! map.containsKey("mango"){
map.put("mango",new ArrayList<>());
}
List<Integer> list = map.get("mango");
list.add(3);
Method 3: Use getOrDefault
Map<String, List<Integer>> map = new HashMap();
List<Integer> list = map.getOrDefault("mango",new ArrayList<>());
list.add(4)
for (Map.Entry<String, ArrayList<Integer>> entry : map.entrySet()) {
System.out.println( entry.getKey());
System.out.println( entry.getValue());//Returns the list of values
}
static HashMap<Integer, ArrayList<Integer>> has(int arr[], int target) {
HashMap<Integer, ArrayList<Integer>> hm = new HashMap<Integer, ArrayList<Integer>>();
for (int i = 0; i < arr.length; i++) {
if (!hm.containsKey(arr[i])) {
ArrayList<Integer> res = new ArrayList<Integer>();
res.add(i + 1);
hm.put(arr[i], res);
} else {
hm.get(arr[i]).add(i);
}
}
return hm;
}
Fetch all at once =
List<Integer> list = null;
if(map!= null)
{
list = new ArrayList<Integer>(map.values());
}
For Storing =
if(map!= null)
{
list = map.get(keyString);
if(list == null)
{
list = new ArrayList<Integer>();
}
list.add(value);
map.put(keyString,list);
}

Sorting by values in HashMap class using Java

I'm trying to get results HashMap sorted by value.
This is HashMap's keys and values:
map.put("ertu", 5);
map.put("burak", 4);
map.put("selin", 2);
map.put("can", 1);
I try to get results like this:
1 = can
2 = selin
4 = burak
5 = ertu
Here is my code:
import java.util.*;
public class mapTers {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("ertu", 5);
map.put("burak", 4);
map.put("selin", 2);
map.put("can", 1);
Integer dizi[] = new Integer[map.size()];
Set anahtarlar = map.keySet();
Iterator t = anahtarlar.iterator();
int a = 0;
while (t.hasNext()) {
dizi[a] = map.get(t.next());
a++;
}
Arrays.sort(dizi);
for (int i = 0; i < map.size(); i++) {
while (t.hasNext()) {
if (dizi[i].equals(map.get(t.next()))) {
System.out.println(dizi[i] + " = " + t.next());
}
}
}
}
}
You can sort the entries as follows (but note this won't sort the map itself, and also HashMap cannot be sorted) -
List<Map.Entry<String, Integer>> entryList = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
Collections.sort(entryList, new Comparator<Map.Entry<String, Integer>>() {
#Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
Every time that you call t.next(), the iterator's pointer is moved forward. Eventually, the iterator reaches the end. You need to reset the iterator. Also, calling t.next() twice moves the pointer twice.
Here's my solution:
import java.util.*;
public class mapTers
{
public static void main(String[] args)
{
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("ertu", 5);
map.put("burak", 4);
map.put("selin", 2);
map.put("can", 1);
Integer dizi[] = new Integer[map.size()];
Set anahtarlar = map.keySet();
Iterator t = anahtarlar.iterator();
int a = 0;
while (t.hasNext())
{
dizi[a] = map.get(t.next());
a++;
}
Arrays.sort(dizi);
for (int i = 0; i < map.size(); i++)
{
t = anahtarlar.iterator();
while (t.hasNext())
{
String temp = (String)t.next();
if (dizi[i].equals(map.get(temp)))
{
System.out.println(dizi[i] + " = " + temp);
}
}
}
}
}
You cannot do that from a Map. At least not directly.
Retrieve the keys/entries, get all the map data in a more suitable structure (hint: a class that encapsulates both attributes and is is stored in a sortable (hint2: SortedSet, List)) and sort.
Do not forget to extend Comparable (and implement compareTo) or, otherwise, create a Comparator.
This is one of the solutions take from: https://stackoverflow.com/a/13913206/1256583
Just pass in the unsorted map, and you'll get the sorted one.
private static Map<String, Integer> sortByComparator(Map<String, Integer> unsortMap, final boolean order) {
List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(unsortMap.entrySet());
// Sorting the list based on values
Collections.sort(list, new Comparator<Entry<String, Integer>>() {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
if (order) {
return o1.getValue().compareTo(o2.getValue());
}
else {
return o2.getValue().compareTo(o1.getValue());
}
}
});
// Maintaining insertion order with the help of LinkedList
Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
for (Entry<String, Integer> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
To print, do a simple iteration over the entry set:
public static void printMap(Map<String, Integer> map) {
for (Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
}
}
You probably have the wrong data structure for this problem. Either:
Reverse the map so the integers are the keys and the words the values and make the map a SortedMap, or
Use a bidirectional map as provided by libraries like Google Guava.
Reversed Map
private final SortedMap<Integer, String> TRANSLATIONS;
static {
SortedMap<Integer, String> map = new TreeMap<>();
map.put(1, "can");
// ...
TRANSLATIONS = Collections.unmodifiableSortedMap(map);
}
Guava BiMap
private final BiMap TRANSLATIONS =
new ImmutableBiMap.Builder<String, Integer>()
.put("ertu", 5);
.put("burak", 4);
.put("selin", 2);
.put("can", 1);
.build();
Then, iterate over a sorted version of the key set or value set as needed. For example,
TRANSLATIONS.inverse.get(4); // "burak"
I'm just curious. What language are your strings in?

Compare HashMap values in an ArrayList

I have an ArrayList and there are some HashMap<String, String> in this. So, I want to compare for same values in the maps. When I find same values then I want to keep one map of them. For example, consider that second map and fifth map (in the arraylist) have the same value. I want to keep the second map and remove the fifth from the arraylist.
i try to do with an iterator, but i can't do it. It seems complicated. Can you give me an example?
This is my last try:
private HashMap<String, String> mapValues = new HashMap<String, String>();
private HashMap<String, String> mapValues2 = new HashMap<String,String>();
private HashMap<Integer, String> mval = new HashMap<Integer, String>();
//i take the ArrayList with the maps for comparison private
ArrayList<HashMap<String, String>> check(ArrayList<HashMap<String, String>> list) {
//a new ArrayList. It will have the maps(HashMap<key, value>) with no same values.
ArrayList<HashMap<String, String>> listFinal = new ArrayList<HashMap<String, String();
for (int i = 0; i < list.size(); i++) {
mapValues = list.get(i);
mval.put(i, mapValues.get("value"));
}
for (int i = 0; i < mval.size(); i++) {
HashMap<String, String> newMapValues = new HashMap<String, String>();
mapValues2 = list.get(i);
String iVal = mapValues2.get("value");
newMapValues = list.get(i);
int flag = -1;
int remove = -1;
for (int j = i+1; j < mval.size()-1; j++) {
String jVal = mval.get(j);
if (val.compareTo(jVal) == 0) {
flag = i;
remove = j;
}
}
if (flag == -1) {
listFinal.add(newMapValues );
} else if (flag != -1) {
listFinal.remove(remove);
}
}
}
Just thinking out loud but my approach would be something like:
Create a Set, where you store the values that you already found in the map.
Each time you get a Map in a new position of the list, check if the element of the Map exists in the Set, if it does, remove the Map from the ArrayList (it's duplicated), if it doesn't, add the value of the Map to the Set and Carry on.
Make sure you remove the Map from the ArrayList using the Iterator's remove method!
List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
//... filling up list and maps...
Set<String> valueSet = new HashSet<String>();
for(Iterator<Map<String, String>> mapIt = mapList.iterator(); mapIt.hasNext();) {
final Map<String, String> map = mapIt.next();
boolean hasDuplicate = false;
for(final String mapValue : map.values()) {
if(valueSet.contains(mapValue))
hasDuplicate = true;
}
if(hasDuplicate)
mapIt.remove();
valueSet.addAll(map.values());
}
Hope someone proofreads this, cause I'm not typing it in an IDE and I haven't had my coffee yet.
EDIT: okay, that previous version was wrong as hell. Check this instead.
EDIT 2: just realized this won't work either. It might remove, say, map 3 because it has a dupe value with map 2, but map 2 is removed because of some other dupe value with map 1. Result: only map 1 is retained and map 2 and 3 are removed but map 3 doesn't have dupes with map 1. This is a bit more complex than I thought. Better get that coffee...
Create a Set<HashMap<String,String>> and add every member of list to it. Problem solved!
If you absolutely need an ArrayList instead of a Set, you can create a new ArrayList from the Set, but either way the lesson is: let Java do the work for you. You are unlikely to do a better job at collection manipulation than the standard library.
package com.test.examples;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.test.vo.CustomerContactVO;
import com.test.vo.CustomerOutPut;
import com.test.vo.CustomerPreferenceVO;
public class TestExampleOne {
public static Map<String, CustomerContactVO> getVO(){
Map<String, CustomerContactVO> contactVOMap = new HashMap<String, CustomerContactVO>();
CustomerContactVO v = new CustomerContactVO();
v.setContactAcctID("60011151");
v.setEmailID("raj#gmail.com");
CustomerContactVO v1 = new CustomerContactVO();
v1.setContactAcctID("60011152");
v1.setEmailID("raj1#gmail.com");
CustomerContactVO v2 = new CustomerContactVO();
v2.setContactAcctID("60011153");
v2.setEmailID("raj2#gmail.com");
CustomerContactVO v3 = new CustomerContactVO();
v3.setContactAcctID("60011154");
v3.setEmailID("raj3#gmail.com");
CustomerContactVO v4 = new CustomerContactVO();
v4.setContactAcctID("60011155");
v4.setEmailID("raj4#gmail.com");
contactVOMap.put("60011151", v);
contactVOMap.put("60011152", v1);
contactVOMap.put("60011153", v2);
contactVOMap.put("60011154", v3);
contactVOMap.put("60011155", v4);
return contactVOMap;
}
public static List<CustomerPreferenceVO> perfVo(){
CustomerPreferenceVO prefVo = new CustomerPreferenceVO();
prefVo.setContactAcctID("60011151");
prefVo.setMktInd("500");
prefVo.setPrefInd("Y");
CustomerPreferenceVO prefVo1 = new CustomerPreferenceVO();
prefVo1.setContactAcctID("60011153");
prefVo1.setMktInd("302");
prefVo1.setPrefInd("N");
CustomerPreferenceVO prefVo2 = new CustomerPreferenceVO();
prefVo2.setContactAcctID("60011154");
prefVo2.setMktInd("302");
prefVo2.setPrefInd("Y");
List<CustomerPreferenceVO> list = new ArrayList<CustomerPreferenceVO>();
list.add(prefVo);
list.add(prefVo1);
list.add(prefVo2);
return list;
}
public static void main(String[] args) {
Iterator<Entry<String, CustomerContactVO>> it = getVO().entrySet().iterator();
List<CustomerOutPut> customerOutPutsList = new ArrayList<CustomerOutPut>();
while(it.hasNext()){
Entry<String, CustomerContactVO> ent = it.next();
String contAcctIDKey = ent.getKey();
String email = ent.getValue().getEmailID();
CustomerOutPut customerOutPut = new CustomerOutPut();
customerOutPut.setContactAcctIDVo(contAcctIDKey);
customerOutPut.setEmailIDVo(email);
for (CustomerPreferenceVO customerPreferenceVO : perfVo()) {
if(customerPreferenceVO.getContactAcctID()!=null &&
customerPreferenceVO.getContactAcctID().equals(contAcctIDKey)){
customerOutPut.setContactAcctIDRef(customerPreferenceVO.getContactAcctID());
customerOutPut.setMktIndRef(customerPreferenceVO.getMktInd());
customerOutPut.setPrefIndRef(customerPreferenceVO.getPrefInd());
}
}
customerOutPutsList.add(customerOutPut);
}
for (CustomerOutPut customerOutPut : customerOutPutsList) {
System.out.println(customerOutPut.toString());
}
}
}
Compare Map keys with Arraylist values
public static void main(String[] args) {
Iterator<Entry<String, CustomerContactVO>> it = getVO().entrySet().iterator();
List<CustomerOutPut> customerOutPutsList = new ArrayList<CustomerOutPut>();
while(it.hasNext()){
Entry<String, CustomerContactVO> ent = it.next();
String contAcctIDKey = ent.getKey();
String email = ent.getValue().getEmailID();
CustomerOutPut customerOutPut = new CustomerOutPut();
customerOutPut.setContactAcctIDVo(contAcctIDKey);
customerOutPut.setEmailIDVo(email);
for (CustomerPreferenceVO customerPreferenceVO : perfVo()) {
if(customerPreferenceVO.getContactAcctID()!=null && customerPreferenceVO.getContactAcctID().equals(contAcctIDKey)){
customerOutPut.setContactAcctIDRef(customerPreferenceVO.getContactAcctID());
customerOutPut.setMktIndRef(customerPreferenceVO.getMktInd());
customerOutPut.setPrefIndRef(customerPreferenceVO.getPrefInd());
}
}
customerOutPutsList.add(customerOutPut);
}
for (CustomerOutPut customerOutPut : customerOutPutsList) {
System.out.println(customerOutPut.toString());
}
}

Categories

Resources