I am using java with mongodb.. I am getting performance issue in this below code can you please optimize this code?
I need to increase the performance of this function.
//first function which receives the parameter as associationId. can you guys please help me to increase the performance for this function..
public ArrayList<ResidentAssociationMapEntity> listUsersByAssociation(String
associationId) {
HashMap<String, Object> filterExpressions = new HashMap<String, Object>();
filterExpressions.put("associationId", associationId);
filterExpressions.put("residentStatus", 1);
List<ResidentAssociationMapEntity> residents =
DBManager.getInstance().getByMultipleFields(
ResidentAssociationMapEntity.class, filterExpressions);
if (residents != null && residents.size() > 0) {
for (ResidentAssociationMapEntity map : residents ) {
map.setUser(getUser(map.getUserId()));
}
}
return new ArrayList<ResidentAssociationMapEntity>(residents);
}
// get user function
public UserEntity getUser(String userId) {
UserEntity entity = DBManager.getInstance().getById(UserEntity.class,
userId);
ResidentAssociationMapEntity map =
getResidentAssocaitionMap(entity.getUserId());
if (map != null) {
entity.setUnitNo(map.getUnitNumber() + "");
entity.setAssociationId(map.getAssociationId());
entity.setAssociationName(CompanyDAO.getInstance().getCompany(map.getAssocia
tionId()).getName());
}
return entity;
}
//getResidentAssocaitionMap function
private ResidentAssociationMapEntity getResidentAssocaitionMap(String
residentId) {
HashMap<String, Object> filterExpressions = new HashMap<String, Object>();
filterExpressions.put("userId", residentId);
filterExpressions.put("residentStatus", 1);
List<ResidentAssociationMapEntity> residents =
DBManager.getInstance().getByMultipleFields(
ResidentAssociationMapEntity.class, filterExpressions);
if (residents != null && residents.size() > 0) {
return residents.get(0);
}
return null;
}
Related
Following this demo: https://github.com/googlesamples/android-media-controller
I have this
if (playbackState == null) {
Log.e(TAG, "Failed to update media info, null PlaybackState.");
return null;
}
Map<String, String> mediaInfos = new HashMap<>();
mediaInfos.put(getString(R.string.info_state_string),
playbackStateToName(playbackState.getState()));
MediaMetadataCompat mediaMetadata = mController.getMetadata();
if (mediaMetadata != null) {
addMediaInfo(
mediaInfos,
getString(R.string.info_title_string),
mediaMetadata.getString(MediaMetadataCompat.METADATA_KEY_TITLE));
addMediaInfo(
mediaInfos,
getString(R.string.info_artist_string),
mediaMetadata.getString(MediaMetadataCompat.METADATA_KEY_ARTIST));
addMediaInfo(
mediaInfos,
getString(R.string.info_album_string),
mediaMetadata.getString(MediaMetadataCompat.METADATA_KEY_ALBUM));
binding.controlsPage.mediaTitle.setText(
mediaMetadata.getString(MediaMetadataCompat.METADATA_KEY_TITLE));
binding.controlsPage.mediaArtist.setText(
mediaMetadata.getString(MediaMetadataCompat.METADATA_KEY_ARTIST));
binding.controlsPage.mediaAlbum.setText(
mediaMetadata.getString(MediaMetadataCompat.METADATA_KEY_ALBUM));
final Bitmap art = mediaMetadata.getBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART);
if (art != null) {
binding.controlsPage.mediaArt.setImageBitmap(art);
} else {
binding.controlsPage.mediaArt.setImageResource(R.drawable.ic_album_black_24dp);
}
// Prefer user rating, but fall back to global rating if available.
RatingCompat rating =
mediaMetadata.getRating(MediaMetadataCompat.METADATA_KEY_USER_RATING);
if (rating == null) {
rating = mediaMetadata.getRating(MediaMetadataCompat.METADATA_KEY_RATING);
}
mRatingUiHelper.setRating(rating);
} else {
binding.controlsPage.mediaArtist.setText(R.string.media_info_default);
binding.controlsPage.mediaArt.setImageResource(R.drawable.ic_album_black_24dp);
mRatingUiHelper.setRating(null);
}
final long actions = playbackState.getActions();
`
I'm interested in getting the current pitch and changing it to the one I want.
I can see this api here https://developer.android.com/reference/androidx/media3/session/MediaController#setPlaybackParameters(androidx.media3.common.PlaybackParameters) does what I want, but it's only for the MediaController, not for the MediaControllerCompat.
I tried doing mController.getMediaController()
https://developer.android.com/reference/kotlin/android/support/v4/media/session/MediaControllerCompat#getMediaController() with no changes at all.
Any ideas?
Here is the piece of code that's bothering me. It does the task but I want to optimize it if possible.
I have list of Entities
Config for each Entity based on ID.
From Config has Tips for each Entity
From Config has Rejects for each Entity
Rejects have ID for each Tip
I get ID of Tip to be reject, remove it from allItems and add it to removeItems
Map<String, String> removeItems = new HashMap<>();
Map<String, Pair<String, Config>> allItems = new HashMap<>();
for(final Entity entity : entities) {
final Config config = Configs
.get(entity.getId());
if (config == null || entity.getTxId() == null) {
continue;
}
if (config.getTips() != null) {
for (final Tip tip : config.getTips()) {
String currentId = entity.getId();
String currentTipId = tip.getTipId();
if(allItems.containsKey(currentTipId)) {
Pair<String, Config> item = allItems.get(currentTipId);
if(tip.getPriority() > item.getValue().getPriority()) {
removeItems.put(currentTipId, item.getKey());
allItems.put(currentTipId, new Pair(currentId, tip));
} else {
removeItems.put(currentTipId, currentId);
}
} else {
allItems.put(currentTipId, new Pair(currentId, tip));
}
List<String> rejects = tip.getRejects();
if(CollectionUtils.isEmpty(rejects)) {
continue;
}
for (String reject : rejects) {
Pair<String, Config> pair = allItems.get(reject);
if (null != pair) {
String rejectId = pair.getKey();
if (StringUtils.isNotEmpty(rejectId)) {
removeItems.put(reject, rejectId);
}
}
}
}
}
}
#CacheRemoveAll not clear cache. Every time when I call getTechnologyColorObjcts(), my data will be cached. but when I call deleteTechnologyColorObjects(), cache is still there.
#Singleton(name = "ThematicTechnologyColorCache")
#Startup
#Lock(LockType.READ)
#CacheDefaults(cacheName = "ThematicTechnologyColorCache")
#Keep
#KeepName
#KeepClassMemberNames
public class ThematicTechnologyColorCache {
#Inject
private WebPortalManager webPortalManager;
#CacheResult(cacheName = "ThematicTechnologyColorCache")
public HashMap<String, List<ThemeText>> getTechnologyColorObjects() {
HashMap<String, List<ThemeText>> technologyColorsList = null;
HashMap<String, Integer> profileIDList = getProfileIDList();
if (profileIDList.size() != 0 && profileIDList != null) {
technologyColorsList = getTechnologyColorList(profileIDList);
}
return technologyColorsList;
}
//This function is not working
#CacheRemoveAll(cacheName = "ThematicTechnologyColorCache")
public void deleteObjects() {
logger.warning("In deleteTechnologyColorObjects");
}
I have a problem with parsing an JSON object inside a JSON object, this is how my JSON file looks like:
{
"index":1,
"name":"Peter",
"status":"Student",
"traditional":true,
"address":
{
"street":"Street1",
"city":"City1",
"ZIP":11000
},
"phoneNumbers":[1231123,123111],
"role":"Programmer"
}
And the parseJson() method:
public String parseJson() {
Integer rbr = 0;
StringReader stringReader = new StringReader(jsonStr);
JsonParser jsonParser = Json.createParser(stringReader);
Map<String, Object> jsonMap = new HashMap<>();
String jsonKeyNm = null;
Object jsonVal = null;
while (jsonParser.hasNext()) {
JsonParser.Event event = jsonParser.next();
if (event.equals(Event.KEY_NAME)) {
jsonKeyNm = jsonParser.getString();
}
else if (event.equals(Event.VALUE_STRING)) {
jsonVal = jsonParser.getString();
}
else if (event.equals(Event.VALUE_NUMBER)) {
jsonVal = jsonParser.getInt();
}
**else if (event.equals(Event.START_OBJECT)) {
if(rbr == 0){
//The rbr is used, since when first time when it starts going through json it will be an *START_OBJECT* event too.
rbr++;
continue;
}
jsonVal = jsonParser.getClass();
}**
else if (event.equals(Event.VALUE_TRUE)) {
jsonVal = (Boolean) true;
}
else if (event.equals(Event.VALUE_FALSE)) {
jsonVal = (Boolean) false;
}
**else if (event.equals(Event.START_ARRAY)) {
jsonVal = event.VALUE_STRING;
}**
else if (event.equals(Event.END_ARRAY)) {
jsonVal = event.VALUE_STRING;
}
jsonMap.put(jsonKeyNm, jsonVal);
}
student.setName((String)jsonMap.get("name"));
student.setIndex((Integer)jsonMap.get("index"));
student.setStatus((String)jsonMap.get("status"));
student.setTraditional((Boolean)jsonMap.get("traditional"));
Address address1 = (Address) jsonMap.get("address");
// Tried this too
//Address address =(Address) jsonMap.get("address").getClass().cast(Adress.class);
}
What it actually returns me when I execute jsonMap.get("address") is Java.util.class type. And I am stuck again, can't manage to extract any data from that.
Any help how I could accept and work with the object I get or any other way I could use to read all the data properly?
Also I have a problem reading Array from JSON, since the methods that JsonParser has are only:
.getBigDecimail()
.getInt()
.getLocation()
.getLong()
.getString()
.getClass()
I have to say that I have done it using The JSON-P object model API, but for my project for my university they are asking me to work with The JSON-P streaming API.
Thanks in advance!
public static String parseJson(InputStream in) {
String key = "student";
Deque<String> stack = new LinkedList<>();
Map<String, Object> map = new HashMap<>();
Object obj = null;
JsonParser parser = Json.createParser(in);
while (parser.hasNext()) {
Event event = parser.next();
if (event == Event.START_OBJECT) {
map.putIfAbsent(key, new HashMap<>());
obj = map.get(key);
stack.push(key);
} else if (event == Event.END_OBJECT) {
stack.pop();
obj = stack.isEmpty() ? null : map.get(stack.element());
} else if (event == Event.START_ARRAY) {
Object tmp = new ArrayList<>();
setValue(obj, key, tmp);
obj = tmp;
} else if (event == Event.END_ARRAY)
obj = stack.isEmpty() ? null : map.get(stack.element());
else if (event == Event.KEY_NAME)
key = parser.getString().toLowerCase();
else {
Object value = null;
if (event == Event.VALUE_STRING)
value = parser.getString();
else if (event == Event.VALUE_NUMBER)
value = parser.getInt();
else if (event == Event.VALUE_TRUE)
value = true;
else if (event == Event.VALUE_FALSE)
value = false;
setValue(obj, key, value);
}
}
Student student = new Student();
student.setName(getMapValue(map, "student", "name"));
student.setIndex(getMapValue(map, "student", "index"));
student.setStatus(getMapValue(map, "student", "status"));
student.setTraditional(getMapValue(map, "student", "traditional"));
student.setRole(getMapValue(map, "student", "role"));
student.setPhoneNumbers(getMapValue(map, "student", "phoneNumbers"));
Address address = new Address();
address.setStreet(getMapValue(map, "address", "street"));
address.setCity(getMapValue(map, "address", "city"));
address.setZip(getMapValue(map, "address", "zip"));
return "";
}
private static void setValue(Object obj, String key, Object value) {
if (obj instanceof Map)
((Map<String, Object>)obj).put(key, value);
else
((Collection<Object>)obj).add(value);
}
private static <T> T getMapValue(Map<String, Object> map, String obj, String key) {
Map<String, Object> m = (Map<String, Object>)map.get(obj.toLowerCase());
return m != null ? (T)m.get(key.toLowerCase()) : null;
}
I am having List<Map<String, String>> testList =new ArrayList<Map<String, String>>(); this way.
I want to eleminate the duplicate maps out of the list based on first 5 keys, last 2 keys are optional.
I tried using linkedhashset it worked fine, but this code is legacy code which has lot of comparators used and i cannot change that and use set.
Set<Map<String, String>> testList = new LinkedHashSet<Map<String, String>>();
ListOfMaps.java
public class ListOfMaps {
Map<String,String> map = new HashMap<String,String>();
List<Map<String, String>> testList =new ArrayList<Map<String, String>>();
public static void main(String[] args) {
ListOfMaps ll = new ListOfMaps();
ll.test();
}
public void test()
{
map = new HashMap<String,String>();
map.put("year", "2015");
map.put("standrad", "second");
map.put("age", "30");
map.put("gender", "M");
map.put("class", "first");
map.put("marks", "100");
map.put("score", "200");
testList.add(map);
map = new HashMap<String,String>();
map.put("year", "2015");
map.put("standrad", "second");
map.put("age", "31");
map.put("gender", "F");
map.put("class", "first");
map.put("marks", "100");
map.put("score", "200");
testList.add(map);
//This map object has duplicate keys year,standrad,age,gender,class same as like first map object .
//so this object should be ignore while adding into list.
//marks and score score keys are optional and need not to be verified.
map = new HashMap<String,String>();
map.put("year", "2015");
map.put("standrad", "second");
map.put("age", "30");
map.put("gender", "M");
map.put("class", "first");
map.put("marks", "100");
map.put("score", "200");
testList.add(map);
System.out.println(testList.toString());
}
}
Can anyone help me in this issue?
Thanks
Having bad design it is hard to solve your problem. Here one way to solve your problem using extra Person class maintaining your legacy code.
public class ListOfMaps {
Map<String, String> map = new HashMap<String, String>();
List<Map<String, String>> testList = new ArrayList<Map<String, String>>();
Set<Person> st = new HashSet<>();
/**
* #param args
*/
public static void main(String[] args) {
ListOfMaps ll = new ListOfMaps();
ll.test();
}
public void test() {
map = new HashMap<String, String>();
map.put("year", "2015");
map.put("standrad", "second");
map.put("age", "30");
map.put("gender", "M");
map.put("class", "first");
map.put("marks", "100");
map.put("score", "200");
if (st.add(new Person(map)))
testList.add(map);
map = new HashMap<String, String>();
map.put("year", "2015");
map.put("standrad", "second");
map.put("age", "31");
map.put("gender", "F");
map.put("class", "first");
map.put("marks", "100");
map.put("score", "200");
if (st.add(new Person(map)))
testList.add(map);
// This map object has duplicate keys year,standrad,age,gender,class
// same as like first map object .
// so this object should be ignore while adding into list.
// marks and score score keys are optional and need not to be verified.
map = new HashMap<String, String>();
map.put("year", "2015");
map.put("standrad", "second");
map.put("age", "30");
map.put("gender", "M");
map.put("class", "first");
map.put("marks", "100");
map.put("score", "200");
if (st.add(new Person(map)))
testList.add(map);
System.out.println(testList.toString());
}
}
class Person {
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((age == null) ? 0 : age.hashCode());
result = prime * result + ((cls == null) ? 0 : cls.hashCode());
result = prime * result + ((gender == null) ? 0 : gender.hashCode());
result = prime * result
+ ((standard == null) ? 0 : standard.hashCode());
result = prime * result + ((year == null) ? 0 : year.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Person)) {
return false;
}
Person other = (Person) obj;
if (age == null) {
if (other.age != null) {
return false;
}
} else if (!age.equals(other.age)) {
return false;
}
if (cls == null) {
if (other.cls != null) {
return false;
}
} else if (!cls.equals(other.cls)) {
return false;
}
if (gender == null) {
if (other.gender != null) {
return false;
}
} else if (!gender.equals(other.gender)) {
return false;
}
if (standard == null) {
if (other.standard != null) {
return false;
}
} else if (!standard.equals(other.standard)) {
return false;
}
if (year == null) {
if (other.year != null) {
return false;
}
} else if (!year.equals(other.year)) {
return false;
}
return true;
}
String year, standard, age, gender, cls, marks, score;
public Person(String year, String standard, String age, String gender,
String cls, String marks, String score) {
this.year = year;
this.standard = standard;
this.age = age;
this.gender = gender;
this.cls = cls;
this.marks = marks;
this.score = score;
}
public Person(Map<String, String> map) {
this.year = map.get("year");
this.standard = map.get("standrad");
this.age = map.get("age");
this.gender = map.get("gender");
this.cls = map.get("class");
this.marks = map.get("marks");
this.score = map.get("score");
}
}