Java compare compare value of hashmap with arraylist - java

I'm really stucked on this problem. I'm not sure if this logic is possible, is there any other whay to achieve what I want?
I'm creating a HashMap like this.
List<String> data1 = new ArrayList();
data1.add("valid1");
data1.add("valid2");
List<String> data2 = new ArrayList();
data2.add("valid3");
data2.add("valid4");
Map<String,ArrayList> hashList = new HashMap();
hashList.put("one",data1);
hashList.put("two",data2);
So the Output will be like this:
{one=[valid1,valid2], two=[valid3,valid4]}
But what am I doing is, i'm reading a file and compare it to hashmap
Code:
String line;
String[] token;
try {
LineIterator it = FileUtils.lineIterator(file,"UTF-8");
while(it.hasNext()){
line = it.nextLine();
token = StringUtils.split(line,(","));
if(token[1].equalsIgnoreCase( //check if its equal to the value of the hashmap){
System.out.println("Valid");
}
}
}
my file looks like this :
test1,valid1,check1
test2,valid3,check2
So what I want to do is, to check if the "token[1]" is valid to the value of hashmap.
Thank you in advance!

Convert the map to list
List<String> list = new ArrayList<String>(map.values());
Then use
list.contains(token[1])
to check if its equal to the list content which is the value of the hashmap

ArrayList<String> check;
check = your_hash_map.get(token[1]);
if(check != null){System.out.println("Valid");}

If you want to get the valid key for the token, the most expensive way of achieving your goal is iterating over the hash keys than iterating over the array value for that key and check if any string inside it matches your conditional.
It should looks like this:
String getValidKey(String token, Map<String, List<String>> hashList) {
for (String key: hashList.keySet()) {
for (String valid: hashList.get(key)) {
if (valid.equalsIgnoreCase(token)) {
return key;
}
}
}
return null;
}
If you only need to know if the token is valid or not this should be enough:
boolean isValid(String token, Map<String, List<String>> hashList) {
for (List<String> list: hashList.values()) {
for (String valid: list) {
if (valid.equalsIgnoreCase(token)) {
return true;
}
}
}
return false;
}

Related

Iterate Map in Java

Entry which needs to compare with the List and get the value from Map which is not there is the List.
for (Map.Entry<String, Object> entry : itemObj.entrySet())
{
System.out.println(entry.getKey());
for (ItemProcessVO processVO : itemDetails2){
if (entry.getKey().equalsIgnoreCase(processVO.getAccount())){
String account = processVO.getAccount();
lstAccVO.add(account);
}
}
}
This is the code i have used.I have Map of entry.getKey() has 6 Values while itemDetail2 has only 5 elements.I need to display only the missing account after comparing.
Simply add an else-statement to your if clause that stores that account in a local variable. Then after your for loops you can do whatever with that.
Hint: you can use loop over Map#keySet() instead of Map#entrySet() and bypass the entries that way.
In the provided example you compared the key with the account, simply use the else- statement to find the missingAccounts to iterate after this loop over them.
List<ItemProcessVO> missingAccounts= new ArrayList<>();
for (Map.Entry<String, Object> entry : itemObj.entrySet())
{
System.out.println(entry.getKey());
for (ItemProcessVO processVO : itemDetails2){
if (entry.getKey().equalsIgnoreCase(processVO.getAccount())){
String account = processVO.getAccount();
lstAccVO.add(account);
}else{
missingAccounts.add(account)
}
}
}
Below code should do the trick. It uses case insensitive comparison and prints remaining keys in the end, more explanation is in comments:
public static void main(String[] args) throws IOException {
Map<String, Object> itemObj = new HashMap<>(); //Your Map
List<ItemProcessVO> itemDetails2 = new ArrayList<>();// Your list
//First, get all the keys of the map
Set<String> keys = new HashSet<>(itemObj.keySet());
//Now, iterate through list and remove the matching items
for(ItemProcessVO processVO : itemDetails2){
String key = pop(keys, processVO.getAccount());
//If key is not null then remove it
if(null != key){
keys.remove(key);
}
}
//Now, iterate through remaining keys and print the values
for(String key : keys){
System.out.println("Missing value " + itemObj.get(key));
}
}
private static String pop(Set<String> set, String key){
if(null == set){
return null;
}else{
for(String element : set){
if(element.equalsIgnoreCase(key)){
return element;
}
}
}
}

how to find if an arraylist contains an element and add the result count to HashMap in Java?

I have a list of workStatuses. Each workStatus has its name and time. I can do workStatus.getName() while iterating through every workStatus.
for (workStatus ws: workStatuses) {
String name = ws.getName();
}
Next I have a list of names called nameList.
List<String> nameList = new ArrayList<String>();
nameList.add("Completed");
nameList.add("Failed");
Now I am using HashMap to count number of workStatuses each name has.So I have to
Iterate through workStatuses.
For each workStatus, find the name.
Check if that name exist in my nameList.
If yes, then increase the
number of Workstatus for that name and put that count on HashMap.
What I have done:
Integer numberOfWorkStatus =0;
Map<String,Integer> hm = new HashMap<String,Integer>();
for(WorkStatus ws: workStatuses) {
if (ws.getName()!=null && nameList.contains(ws.getName())) {
numberOfWorkStatus++;
hm.put(ws.getName(), numberOfWorkStatus);
}
}
return hm;
Can anyone suggest me if I am doing it the right way?
You can use stream API and if I get right do something like this:
// List<WorkStatus> workStatuses = ...
workStatuses.stream().collect(
Collectors.groupingBy(WorkStatus::getName, Collectors.counting()));
as a result you will have Map<String, Long>
You can do that this way :
for(Stirng name :nameList)
hm.put(name, 0);
for(WorkStatus ws: workStatuses) {
if( hm.get(ws.getName() != null)
hm.put(ws.getName(), hm.get(ws.getName()) + 1);
}
hm will contains the count of each name that is exists in the workStauses.
You can change this to :
for (String str:nameList){
if (str.contains(ws.getName())) {
totalCount++;
hm.put(ws.getName(), totalCount);
}
}
You cannot check for a String directly from a list and the one you put in HM should be ws.
Map<String, Integer> hm = new HashMap<>();
for (WorkStatus ws : workStatuses) {
if (ws.getName() != null && nameList.contains(ws.getName())) {
hm.putIfAbsent(ws.getName(), 0);
hm.put(ws.getName(), hm.get(ws.getName()) + 1);
}
}

How to split a string into a map with a list of values?

I am a bit stuck with my application, and I am not quite sure what to search for. So I am hoping someone here may help me out.
I have a list of Strings, that looks like this:
Cake;carrot
Cake;apple
Cake;spicy
Pizza;pepperoni
Pizza;mozzarella
... and so on. I want to put this data into a Map<String, List<String>>, where Cake and Pizza will make up the keys in my Map. Having [carrot, apple, spicy] as Cake's values, and [pepperoni, mozzarella] as Pizza's values.
How may I achieve this? Thanks in advance for any help.
Just iterate over your list using String.split()
ArrayList<String> myList;
HashMap<String, List<String>> myMap = new HashMap<>();
for(String s : myList)
{
String[] split = s.split(";");
List<String> bucket = myMap.get(split[0]);
if(bucket == null)
{
bucket = new ArrayList<String>();
myMap.put(split[0], bucket);
}
bucket.add(split[1]);
}
You can try this, use a hashmap, store consecutive strings with (space) as the delimiter, finally split the string when you want it as a list
//Assuming your list to be the variable 'list'
HashMap<String,String> hm = new HashMap<>();
for(val : list){
String st[] = val.split(";");
if(hm.get(st[0])==null){
hm.put(st[0],st[1]);
}
else{
hm.put(st[0],hm.get(st[0])+" "+st[1]);
}
}
when You want the string array of say pizza back then
String pizz[] = (hm.get("pizza")).split(" ");
pizz[] will have your array, cheers!
public static void main(String[] args) {
List<String> data = new ArrayList<String>();
Map<String, List<String>> finalData = new HashMap<String,List<String>>();
data.add("Cake;carrot");
data.add("Cake;apple");
data.add("Cake;spicy");
data.add("Pizza;pepperoni");
data.add("Pizza;mozzarella");
for (String dataString : data) {
List<String> temp = null;
if (finalData.get(dataString.split(";")[0]) == null) {
temp = new ArrayList<String>();
temp.add(dataString.split(";")[1]);
finalData.put(dataString.split(";")[0], temp);
} else {
temp = finalData.get(dataString.split(";")[0]);
temp.add(dataString.split(";")[1]);
finalData.put(dataString.split(";")[0], temp);
}
}
System.out.println(new Gson().toJson(finalData));
}
Complete working solution.

Returning HashMap values and keys through an array method

I'm trying to return keys and values through an array method.
I have done this:
public ArrayList<String> translationList() {
for (String key : translations.keySet()) {
System.out.println(key + " = ");
}
return new ArrayList<String>(this.translations.values());
}
And in my Main.java
ArrayList<String> translations = dictionary.translationList();
for (String translation : translations) {
System.out.println(translation);
}
It returns
apina =
cembalo =
banaani =
monkey
harpsichord
banana
I'm not sure how to get them to print on the same line after the translation of the word. I know it's printing the for loop before returning the array but that is where my problem is and not sure how to solve it.
Since you are getting only values back there is no way to get key based on value. So hence not possible.
What you can do is return keys from method and iterate that in your method.
or simply change your method to
public ArrayList<String> translationList() {
List<String> returnList = new ArrayList<>(String);
for (Entry<Integer, String> entry : testMap.entrySet()) {
returnList.add(entry.getKey()+"="+entry.getValue());
}
return returnList;
}
and in your main method
ArrayList<String> translations = dictionary.translationList();
for (String translation : translations) {
System.out.println(translation);
}

How to check if TreeMap<String, ArrayList<String>> contains a value? in Java

I'm just wondering how to check if TreeMap> contains a value in Java?
For Example:
/*I have TreeMap<String,ArrayList<String>> map with these elements
* {color = ["red","blue","green"], shape=["square", "circle"]}
*/
System.out.println(map.containsValue("square")); //This return false
System.out.println(map.values().contains("square")); //This return false also
I always get false when I use containsValue() or contains() method. Anybody know why and can give me suggestions, please?
Thanks
Ed
Something like below would work
Map<String,ArrayList<String>> map=new TreeMap<String, ArrayList<String>>();
Collection<ArrayList<String>> values=map.values();
for(ArrayList<String> list:values)
{
list.contains("text_to_search")
{
}
}
You're testing to see whether the map contains a String, "square"-- but the values in your map are ArrayList<String> objects.
If you know that you're looking for a shape, you can first get the "shape" list, and test to see whether it contains the specific shape "square".
ArrayList<String> shapes = map.get("shape");
boolean containsSquare = shapes.contains("square");
public boolean valueExists(String value){
for(Map.Entry<String,ArrayList<String>> entry : treeMap.entrySet()) {
String key = entry.getKey();
ArrayList<String> values = entry.getValue();
for (String str:values){
if (value.equals(str)){
return true;
}
}
}
return false;
}

Categories

Resources