I have two java classes:
public class MyClass1 {
private String userId;
private String userName;
private List<CustomList1> customList1;
// getters and setters
// inner CustomList1 class
}
public class MyClass2 {
private String userId;
private List<CustomList2> customList2;
// getters and setters
// inner CustomList2 class
}
Now, I have have lists of these classes:
List<MyClass1> classOneList;
List<MyClass2> classTwoList;
In both classOneList and classTwoList lists, object should be sorted with userId ascending. userId in both lists should have same values. What I want to check is that:
Has both lists same size? If not, thow error exception about.
Has every next element from both list the same userId? If not, throw another exception.
Step 1. I have done with simply if statement.
By prototype, step 2. should look like this:
for (el1, el2 : classOneList, classTwoList) {
el1.getUserId().isEqualTo(el2.getUserId());
}
Try the below code for your problem.
public class Testing {
public static void main(String[] args) {
Map<String, List<String>> map1 = new LinkedHashMap<String, List<String>>();
List<String> m1l1 = new LinkedList<String>();
m1l1.add("One");
m1l1.add("Two");
m1l1.add("Three");
m1l1.add("Four");
map1.put("1", m1l1);
List<String> m1l2 = new LinkedList<String>();
m1l2.add("One");
m1l2.add("Two");
m1l2.add("Three");
m1l2.add("Four");
map1.put("2", m1l2);
// Add more element into the map1 by creating more list.
Map<String, List<String>> map2 = new LinkedHashMap<String, List<String>>();
List<String> m2l1 = new LinkedList<String>();
m2l1.add("One");
m2l1.add("Two");
m2l1.add("Three");
m2l1.add("Four");
map2.put("1", m2l1);
// Add more element into the map2 by creating more list.
for (Entry<String, List<String>> entry : map1.entrySet()) {
if (map2.containsKey(entry.getKey())) {
if (entry.getValue().size() == map2.get(entry.getKey()).size()) {
} else {
System.out.println("UserId are same but list are different for userid: " + entry.getKey());
}
}
else {
System.out.println("Userid '"+entry.getKey()+"' exists in map1 but is not found in map2");
}
}
}
}
Hope this may help you.
if(classOneList.size() != classTwoList.size()){
throw new ErrorException();
}else{
classOneList = classOneList.stream().sorted(Comparator.comparing(MyClass1::getUserId)).collect(Collectors.toList());
classTwoList = classTwoList.stream().sorted(Comparator.comparing(MyClass2::getUserId)).collect(Collectors.toList());
for (int i = 0; i < classOneList.size(); i++){
if(!classOneList.get(i).getUserId().equals(classTwoList.get(i).getUserId())){
throw new AnotherErrorException();
}
}
}
Related
Declaration:-
private static HashMap<String, HashMap<String, ArrayList>> parentMap = new HashMap<>();
private static HashMap<String, ArrayList> childMap = new HashMap<>();
How do I want to store data in hashmap?
"India":
"EmployeeName":[A,B,C]
"China":
"EmployeeName":[D,E,F]
Methods used:-
public static ArrayList<String> getMap(String parentkey, String childKey) {
return parentMap.get(parentkey).get(childKey);
}
public static ArrayList<String> setMap(String parentkey, String childKey, String value) {
childMap.computeIfAbsent(childKey, k -> new ArrayList<>()).add(value);
parentMap.put(parentkey, childMap);
return getMap(parentkey, childKey);
}
setMap("India", "EmployeeName", "A")
setMap("India", "EmployeeName", "B")
setMap("India", "EmployeeName", "C")
setMap("China", "EmployeeName", "D")
setMap("China", "EmployeeName", "E")
setMap("China", "EmployeeName", "F")
How data get stored and printed in hashmap while fetchng from getMap method:
System.out.println("India" + getMap("India").get("EmployeeName"));
System.out.println("China" + getMap("China").get("EmployeeName"));
"India" [A,B,C,D,E,F]
"China" [A,B,C,D,E,F]
Whilst i know keeping the childKey name unique would do thejob for me but I wish to keep the same childKey name under each parentkey name and store the respecive value in arraylist.
Any solution to my problem is welcome.
The problem is that you keep reusing the same childMap, regardless of which parentKey is being used. You need to look up the respective child map when adding values.
That means that childMap should be a local variable, nothing more. Delete your private static HashMap<String, ArrayList> childMap.
Try this:
public static ArrayList<String> setMap(String parentkey, String childKey, String value) {
HashMap<String, ArrayList> childMap = parentMap.computeIfAbsent(parentkey, k->new HashMap<>());
childMap.computeIfAbsent(childKey, k -> new ArrayList<>()).add(value);
return getMap(parentkey, childKey);
}
Proof that this works
Suggestion, don't have generic types and dont have static params
private HashMap<String, HashMap<String, ArrayList<String>>> parentMap = new HashMap<>();
private HashMap<String, ArrayList<String>> childMap = new HashMap<>();
Try to replace this method
public ArrayList<String> setMap(String parentkey, String childKey, String value) {
childMap.putIfAbsent(childKey, new ArrayList<>()); // inserts a key only if the key is not already present
childMap.get(childKey).add(value); // puts the value in the existing key and
if (!parentMap.containsKey(parentkey)) { // puts in the parent map only if not present.
parentMap.put(parentkey, childMap);
}
}
Since the childmap is referenced already, No need to put again.
If I was you I will do it in more "OOP way" so that you can benefit from static typing. Something like:
import java.util.List;
class Employee{
String name;
String getName(){
return name;
}
}
public class CompanyBranch{
String national;
List<Employee> employees;
List<String> getEmployeeAllName(){
return employees.stream().map(Employee::getName).toList();
}
}
I save my data in hashmap. I have two hashmap data, one from database and one from activity result. I want to do some equation with that data, but only if key in activity math with database key. I try to substract activity data with the database data, but the result is always 0.
Data from database and result activity is passed to this hashmap class:
public class PositionData implements Serializable {
private String name;
public HashMap<String, Integer> values;
public HashMap<String,String> routers;
public PositionData(String name) {
// TODO Auto-generated constructor stub
this.name=name;
values = new HashMap<String, Integer>();
routers = new HashMap<String, String>();
}
public void addValue(Router router,int strength){
values.put(router.getBSSID(), strength);
routers.put(router.getBSSID(),router.getSSID());
}
public String getName() {
return name;
}
public String toString() {
String result="";
result+=name+"\n";
for(Map.Entry<String, Integer> e: this.values.entrySet())
result+=routers.get(e.getKey())+" : "+e.getValue().toString()+"\n";
return result;
}
public HashMap<String, Integer> getValues() {
return values;
}
public HashMap<String, String> getRouters() {
return routers;
}
And this is how i do substraction in activity class:
PositionData positionData = (PositionData) intent
.getSerializableExtra("PositionData");
positionsData=db.getReadings(building);
HashMap<String, Integer> rssi = positionData.getValues();
HashMap<String, Integer> rssi1 = positionsData.get(0).getValues();
HashMap<String, String> dest = positionsData.get(0).getRouters();
int dista = 0;
if (positionData.equals(dest)){
dista = Integer.parseInt(String.valueOf(rssi))-Integer.parseInt(String.valueOf(rssi1));
}
Log.v("dis:", String.valueOf(dista));
I have data from class database and class result, both data is passed to HashMap activity to get positionData form. After i get the form, i calculate it in equation class. So, here i have 4 class.
I create generic example for you. I think that can help you understand how you can do equation on your hashmaps.
HashMap<String, Integer> activity= new HashMap<String, Integer>();
HashMap<String, Integer> database = new HashMap<String, Integer>();
Iterator iter = activity.keySet().iterator(); // getting iterator from keySet from one of hashmaps
// Iterate through one of hashmaps keys
while(iter.hasNext()){
String s = (String) iter.next();
if(database.containsKey(s)){ // finding key in second hashmap
// in here you can do your equation;
}
}
It appears that you are trying to compare the contents of a HashMap to object PositionData. You may have to override PositionData's .equals() method so it knows how to compare its contents to a HashMap. Maybe something like the following:
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o instanceof Map) {
Map m = (HashMap) o;
/* loop through both data structures and compare, return true if same */
}
/* compare two instances of PositionData */
return false;
Another option is to write a method to iterate through both and compare their contents, without the need of using/overriding .equals().
I have a Map and a HashSet.
The goal is to check the contents of the Set against the Map and add it to the Map if the elements are there in the HashSet but not in the Map.
// Map is defined in a class
private final Map<String, A> sb = new ConcurrentHashMap<>();
public void someMethod() {
Set<A> hSet = new HashSet<>();
for (A a : ab){
hSet.add(a..a...);
// Check if all elements added to hash Set are there in a Map
// if not present, add it to Map
}
}
if you want to search in map values:
if(!map.values().contains(a))
// put a in the map
if you want to look for keys
if(!map.containsKey(a))
// put a in the map
keep in mind that contains calls equals so in your A class you have to implement hashCode and equals.
public static void main(String[] args) {
Set<String> set = Stream.of("a","b","c","d").collect(Collectors.toSet());
Map<String, String> map = new HashMap<String, String>();
map.put("a", "foo");
map.put("h", "bar");
map.put("c", "ipsum");
for (String string : set) {
if(!map.containsKey(string)) {
map.put(string,string);
}
}
System.out.println(map);
}
output
{a=foo, b=b, c=ipsum, d=d, h=bar}
for (String element : hSet) {
if (!sb.containsKey(element)) {
sb.put(element, A);
}
}
Following could also be solution:
private final Map<String, A> sb = new ConcurrentHashMap<>();
public void someMethod() {
Set<String> set = new HashSet<>();
set.stream().filter(word -> !sb.containsKey(word))
.forEach(word -> sb.put(word, correspondingValueOfTypeA));
}
I'm trying to push my resultset data onto a nested map. Honestly, I've been struggling with the logic of how to do it. Here's a sample of my resultset data,
ID Main Sub
1 Root Carrots
2 Root Beets
3 Root Turnips
4 Leafy Spinach
5 Leafy Celery
6 Fruits Apples
7 Fruits Oranges
I created a hashmap HashMap<Integer, HashMap<String, List<String>>>, in which I thought the innermap could hold the main col as key and the corresponding subs as the list of values. The outermap would contain the id as the key and the corresponding map as the value. I'm struggling to achieve this.
Any help would be appreciated.
I would suggest using a different structure.
You have unique Id's and sub, but your Main can be duplicate.
Thus I would suggest using the following structure:
HashMap>
where POJO has ID and sub.
the key of map would be main.
Thus you can easily do:
if (map.get(main)==null){
List<POJO> pojoList= new List<>();
pojolist.add(pojo);
}else{
List<POJO> pojoList=map.get(main);
pojoList.add(pojo);
}
But it ultimately depends if you need to do lookup using ID or main.
Below is the answer to your question. But the question is probably wrong. Since the ID is unique (just a guess) you're probably looking for
Map<Integer, DataObject> map = new HashMap<>();
where DataObject is a POJO containing the variabels main and sub. Adding data to such a structure is easy.
Answer to question (added to show you how Maps and Lists work):
private Map<Integer, Map<String, List<String>>> map = new HashMap<>();
public static void main(String[] args) {
new Tester().go();
}
private void go() {
add(1, "Root", "Carrots");
add(2, "Root", "Beets");
add(3, "Root", "Turnips");
add(4, "Leafy", "Spinach");
add(5, "Leafy", "Celery");
add(6, "Fruits", "Apples");
add(7, "Fruits", "Oranges");
}
private void add(int id, String main, String sub) {
if (!map.containsKey(id)) {
map.put(id, new HashMap<String, List<String>>());
}
ArrayList<String> list = new ArrayList<String>();
list.add(sub);
map.get(id).put(main, list);
}
There is no need to make nested hash maps because each row in the example is unique (each List in nested map will have only one value).
In any case here is algorithm example in Java 8 style for your particular need :
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<ResultSet> rows = new ArrayList<>();
rows.add(new ResultSet().setId(1).setMain("Root").setSub("Carrots"));
rows.add(new ResultSet().setId(2).setMain("Root").setSub("Beets"));
rows.add(new ResultSet().setId(3).setMain("Root").setSub("Turnips"));
rows.add(new ResultSet().setId(4).setMain("Leafy").setSub("Spinach"));
rows.add(new ResultSet().setId(5).setMain("Leafy").setSub("Celery"));
rows.add(new ResultSet().setId(6).setMain("Fruits").setSub("Apples"));
rows.add(new ResultSet().setId(7).setMain("Fruits").setSub("Oranges"));
HashMap<Integer, HashMap<String, List<String>>> result = new HashMap<>();
rows.forEach(row -> {
HashMap<String, List<String>> subsByMain = result.getOrDefault(row.getId(), new HashMap<>());
List<String> subs = subsByMain.getOrDefault(row.getMain(), new ArrayList<>());
subs.add(row.getSub());
subsByMain.put(row.getMain(), subs);
result.put(row.getId(), subsByMain);
});
}
static class ResultSet {
private Integer id;
private String main;
private String sub;
Integer getId() {
return id;
}
ResultSet setId(Integer id) {
this.id = id;
return this;
}
String getMain() {
return main;
}
ResultSet setMain(String main) {
this.main = main;
return this;
}
String getSub() {
return sub;
}
ResultSet setSub(String sub) {
this.sub = sub;
return this;
}
}
}
This is my first question in Stackoverflow.I have come to find a issue with one of the problem suggested and give to me by my colleague to do some research on it.
My question is
i have a class
Class Function{
String func;
String funcname;
boolean log;
}
i have created some objects:
obj1 : ("a" ,"b",true)- //these values come from either DB or UI
obj2 : ("c" ,"x",true)
obj3 : ("a" ,"z",true)
i have a list:
List<function> flist;
now i want to have that list in the map and want to put in inside the map
Map<String, List<function>> funcMap
and then display this following output:
a:[obj1 obj3]
b:[obj2]
if i have the list but how to go about and find the above output as desired
Try this,
add all the objects in the flist.
initialize the map
Map<String, List<Function>> funcMap = new HashMap<String, List<Function>>();
going to add the object to the relevant key based on the func value the object will add to the value list.
for (Function functionValue : flist)
{
List<Function> functionList = funcMap.get(functionValue.getFunc());
if (functionList != null && !functionList.isEmpty())
{
functionList.add(functionValue);
}
else
{
functionList = new ArrayList<Function>();
functionList.add(functionValue);
funcMap.put(functionValue.getFunc(), functionList);
}
}
Atlast print the funcMap
for (Map.Entry< String, List<Function>> entry : funcMap.entrySet())
{
System.out.println("Key : " + entry.getKey() + "Values : "+entry.getValue());
}
Hmm.. I think it's a case of parsing your list in a nested loop kind of way. Here is the pseudo-code:
public void listToMap(List<Function> list)
{
Map<String, List<Function>> map := new Map
for every function in the list.
{
if(is the current function's func value does not exist in the map)
{
func := current functions func value
List matchingFunctions := new list of Functions.
for(every function in the list.)
{
// Every Function with the same key get's added to a list.
if(function has the same func value as func)
{
add to matchingFunctions.
}
}
// That list and key get put into the HashMap.
map.put(func, matchingFunctions).
}
}
}
A Note on your code design
Java convention states that you should wrap your member objects up in getters and setters, and that those members should be private.
what about:
public class FuncTest {
public static void main(String[] args) {
new FuncTest().start();
}
private void start() {
List<Function> flist = new ArrayList<Function>();
flist.add(new Function("a", "b", true));
flist.add(new Function("c", "x", true));
flist.add(new Function("a", "z", true));
Map<String, List<Function>> funcMap = new HashMap<String, List<Function>>();
for (Function func : flist) {
this.add(func.func, func, funcMap);
this.add(func.funcname, func, funcMap);
}
}
private void add(String field, Function func, Map<String, List<Function>> funcMap) {
List<Function> subList = funcMap.get(field);
if (subList == null) {
subList = new ArrayList<Function>();
funcMap.put(field, subList);
}
subList.add(func);
}
}
Note
As already mentioned by Chris you should think about your code design. Use getters and setters ..
public class Stackoverflow {
public static void main(String[] args) {
Function obj1 = new Function("a" ,"b",true);
Function obj2 = new Function("c" ,"x",true);
Function obj3 = new Function("a" ,"z",true);
List<Function> functionsList1 = new ArrayList<Function>();
functionsList1.add(obj1);
functionsList1.add(obj3);
List<Function> functionsList2 = new ArrayList<Function>();
functionsList2.add(obj2);
Map<String, List<Function>> funcMap = new LinkedHashMap<String, List<Function>>();
funcMap.put("a", functionsList1);
funcMap.put("b", functionsList2);
Set<Entry<String,List<Function>>> entrySet = funcMap.entrySet();
for (Entry<String, List<Function>> entry : entrySet) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
}
class Function {
String func;
String funcname;
boolean log;
public Function(String func, String funcname, boolean log) {
super();
this.func = func;
this.funcname = funcname;
this.log = log;
}
#Override
public String toString() {
return "Function [func=" + func + ", funcname=" + funcname + ", log="
+ log + "]";
}
}
Write your own map.
Pass the list to map, let map will decide what portion of list to keep as value.
I have added put method here, like the same, have to Override other methods.
class MyHashMap<K,V> extends HashMap<K,V>{
#SuppressWarnings("unchecked")
public V put(K k, V v) {
String key = (String)k;
List<Function> list = (List<Function>) v;
List<Function> list2 = new ArrayList<Function>();
for (Function function : list) {
if(key.equalsIgnoreCase(function.func)){
list2.add(function);
}
}
return (V) list2;
};
#Override
public boolean equals(Object o) {
// Your own code
return true;
}
// other methods goes here..
}