I have POJO List<TravelRequestDTO> and I want to group and create filtered List<TravelRequestDTO> if leavingFrom,goingTo,onwarDate,returnDate are same add passenger to same object
Example :
Passanger, onWard, return, leavingFrom, goingTo
A, 1-2-20, 3-2-20, BLR, PUNE
B, 1-2-20 , 3-2-20, BLR, PUNE
final List<TravelRequestDTO> should contain :
Passanger, onWard, return, leavingFrom, goingTo
A,B 1-2-20 3-2-20 BLR PUNE
public class TravelRequestDTO {
private List<Pax> passangers;
private String leavingFrom;
private String goingTo;
private String onwarDate;
private String onwardTime;
private String returnDate;
private String returnTime;
private SegmentTypeEnum segmentType;
private TravelModeEnum travelMode;
private String purposeOfVisit;
}
public class Pax{
private String name;
private String age;
private String mobile;
}
If you need older java version, than you can do like this:
Map<Object, List<TravelRequestDTO>> hashMap = new HashMap<Object, List<TravelRequestDTO>>();
for (TravelRequestDTO value: initList) {
List<Object> key = Arrays.asList(value.getOnWard(),value.getReturn(),value.getLeavingFrom(),value.getGoingTo());
if (!hashMap.containsKey(key)) {
List<TravelRequestDTO> list = new ArrayList<TravelRequestDTO>();
list.add(value);
hashMap.put(key, list);
} else {
hashMap.get(key).add(value);
}
}
Check this question for other solution.
It is only half way to what you want. After that you have to extract final result from this map. Or you can do it in one step:
Map<Object, TravelRequestDTO> hashMap = new HashMap<Object, TravelRequestDTO>();
for (TravelRequestDTO value: initList) {
List<Object> key = Arrays.asList(value.getOnWard(),value.getReturn(),value.getLeavingFrom(),value.getGoingTo());
if (!hashMap.containsKey(key)) {
TravelRequestDTO item = value; // pass first value or copy it to new
hashMap.put(key, item);
} else {
hashMap.get(key).getPassangers().addAll(value.getPassangers());
}
}
List<TravelRequestDTO> result = new ArrayList<>(hashMap.values());
you can use the below code to get a List of TravelRequestDTO objects based on properties.
Function<TravelRequestDTO, List<Object>> compositeKey = travelRecord ->
Arrays.<Object>asList(travelRecord.getOnWard(),travelRecord.getReturn(),travelRecord.getLeavingFrom(),travelRecord.getGoingTo());
Map<Object, List<TravelRequestDTO>> map =
people.collect(Collectors.groupingBy(compositeKey, Collectors.toList()));
I know this is a noob a question, but I couldn't find a simpe answer anywhere else. Question is: I need to write a method that returns a SortedMap, so a tree map should work just fine.
I have a HashMap< String, Skill>, the Skill class has both the methods getName and getNumApplicants and I need to return a SortedMap<String, Long>, with the name of the skill as a key and the number of applicants as value. This is where I stand:
private Map<String,Skill> skillMap = new HashMap<>();
public SortedMap<String, Long> skill_nApplicants() {
return skillMap.values().stream().collect(...);
}
This is the Skill class
public class Skill {
private String name;
private List <Position> reqPosition = new ArrayList<>();
private Long numApplicants;
public void plusOneApplicant() {
this.numApplicants++;
}
public Long getNumApplicants() {
return numApplicants;
}
public Skill(String name) {
super();
this.name = name;
this.numApplicants = 0L;
}
public String getName() {
return name;
}
public List<Position> getPositions() {
return reqPosition;
}
public void addReqPosition(Position p) {
this.reqPosition.add(p);
return;
}
}
I know this should be very easy, I just have a very hard time in understanding this all thing.
Don't collect the data to a HashMap first, then convert to a TreeMap. Collect the data directly to a TreeMap by using the overloaded toMap(keyMapper, valueMapper, mergeFunction, mapSupplier) method that allows you to specify which Map to create (4th parameter).
public SortedMap<String, Long> skill_nApplicants() {
return skillMap.values().stream().collect(Collectors.toMap(
Skill::getName,
Skill::getNumApplicants,
Math::addExact, // only called if duplicate names can occur
TreeMap::new
));
}
This is how you can do it
public SortedMap<String, Long> skill_nApplicants(Map<String, Skill> skillMap) {
Map<String, Long> result = skillMap.values().stream().collect(Collectors.toMap(Skill::getName, Skill::getNumApplicants));
return new TreeMap<>(result);
}
If, in your stream, you don't have two (or more) values which should be mapped with the same key, then you can avoid to use a Collector at all (and thus you don't need to think about a merge function).
All you need to do is to simply add each skill to the map with a forEach:
public SortedMap<String, Long> skill_nApplicants() {
Map<String, Long> result = new TreeMap<>();
skillMap.values()
.forEach((skill) -> result.put(skill.getName(), skill.getNumApplicants());
return result;
}
You can wrap result with Collections.unmodifiableSortedMap if you want to return an unmodifiable map.
I'm reviewing an old code of an project and got a datastructure as bellow using Map of Map of Map(3-Layered Map):
// data structure
Map<String, Map<String, Map<String, List<String>>>> tagTree
= new HashMap<String, Map<String,Map<String,List<String>>>>();
And fetch the values from Map (I think this is the nice part)
// fetch at tag values
List<String> tagList1 = tagTree.get("Java").get("Active").get("Tags");
List<String> tagList2 = tagTree.get("Java").get("Latest").get("SubTags");
Put the values in Map (little bit complex and error-prone)
// put values
Map<String, Map<String, List<String>>> javaLangMap = new HashMap<String, Map<String, List<String>>>();
Map<String, List<String>> javaStatusMap = new HashMap<String, List<String>>();
List<String> javaTagList = new ArrayList<String>();
javaTagList.add("Java-OOP");
javaTagList.add("Java-Variables");
// put tag list
javaStatusMap.put("Tags", javaTagList);
// put status-wise tag
javaLangMap.put("Active", javaStatusMap);
// put language-wise tag
tagTree.put("Java", javaLangMap);
Currently this is serving to maintain following structure
TagLanguage -> TagStatus -> TagType -> TagList
I'm planning to refactor this Map because it's hard to read for other developers.
Please share your Idea How to do it by considering following cases:
All four layer may be changed during runtime.
All Level should
accessible
In-memory solution required i.e. dont use Database table hierarchy .
If you only ever wanted to access the last level of your data structure, you could use a Multimap<Triple<String,String,String>,String>. Multimap<K,V> is a data structure from Guava which basically is a nicer Map<K,Collection<V>>. Triple<L,M,R> is a 3-elements tuple data structure from Apache Commons Lang3 which is Comparable and implements equals.
You could declare your tag tree like this:
Multimap<Triple<String, String, String>, String> tagTree = HashMultimap.create();
And then fill it like this:
tagTree.put(Triple.of("Java", "Active", "Tags"), "Java-OOP");
tagTree.put(Triple.of("Java", "Active", "Tags"), "Java-Variables");
Or:
tagTree.putAll(Triple.of("Java", "Active", "Tags"), Arrays.asList("Java-OOP", "Java-Variables"));
And then get your values from it like this:
Set<String> values = tagTree.get(Triple.of("Java", "Active", "Tags"));
Here is another rough solution that may suit you which enables to get with 1, 2 or 3 keys:
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
public class ThreeLevelMap<K1, K2, K3, V> {
private Map<K1, Map<K2, Multimap<K3, V>>> firstLevelMap = new HashMap<>();
private Map<Pair<K1, K2>, Multimap<K3, V>> secondLevelMap = new HashMap<>();
private Multimap<Triple<K1, K2, K3>, V> thirdLevelMap = HashMultimap.create();
public void put(K1 key1, K2 key2, K3 key3, V value) {
thirdLevelMap.put(Triple.of(key1, key2, key3), value);
final Pair<K1, K2> secondLevelKey = Pair.of(key1, key2);
Multimap<K3, V> secondLevelContainer = secondLevelMap.get(secondLevelKey);
if (secondLevelContainer == null) {
secondLevelContainer = HashMultimap.create();
secondLevelMap.put(secondLevelKey, secondLevelContainer);
}
secondLevelContainer.put(key3, value);
Map<K2, Multimap<K3, V>> firstLevelContainer = firstLevelMap.get(key1);
if (firstLevelContainer == null) {
firstLevelContainer = new HashMap<>();
firstLevelMap.put(key1, firstLevelContainer);
}
firstLevelContainer.put(key2, secondLevelContainer);
}
public Collection<V> get(K1 key1, K2 key2, K3 key3) {
return thirdLevelMap.get(Triple.of(key1, key2, key3));
}
public Multimap<K3, V> get(K1 key1, K2 key2) {
return secondLevelMap.get(Pair.of(key1, key2));
}
public Map<K2, Multimap<K3, V>> get(K1 key1) {
return firstLevelMap.get(key1);
}
}
You can use it this way:
ThreeLevelMap<String, String, String, String> tlm = new ThreeLevelMap<>();
tlm.put("Java", "Active", "Tags", "Java-OOP");
tlm.put("Java", "Active", "Tags", "Java-Variables");
Map<String, Multimap<String, String>> firstLevelMap = tlm.get("Java");
Multimap<String, String> secondLevelMap = tlm.get("Java", "Active");
Collection<String> tags = tlm.get("Java", "Active", "Tags");
I say it is rough because:
the maps that the get methods return are modifiable
I didn't implement remove methods
I didn't test it a lot
I don't think that this is such a bad solution.
It's just a tree representation, for a tree where every leaf is at level 3.
If this was not the case (different leaf levels, etc.) you would have to build up a tree class structure.
But what I would change is to put everything in a class, with a get and set method, including null-checks.
In the following code, the add method takes care of the error-prone handling of the intermediate level maps, while get checks for null values in the intermediate levels:
public class TreeStructure {
Map<String, Map<String, Map<String, List<String>>>> tagTree
= new HashMap<String, Map<String,Map<String,List<String>>>>();
// ... Constructor ...
// This method adds all intermediate levels if not existing
public void add(String level1, String level2, String level3) {
String l1 = tagTree.get(level1);
if(l1 == null)
tagTree.put(level1, new HashMap<String, Map<String, List<String>>>());
l1 = tagTree.get(level1);
String l2 = l1.get(level2),
if(l2 == null)
tagTree.put(level2, new Map<String, List<String>>(););
l2 = l1.get(level2);
String l3 = l2.get(level3);
if(l3 == null) l2.add(level3, new ArrayList<>());
}
// This method checks, if every intermediate level existed
// Otherwise, get() returns null, and the next get() would fail
public String get(String level1, String level2, String level3) {
String l1 = tagTree.get(level1);
if(l1 == null)
return null;
String l2 = l1.get(level2),
if(l2 == null)
return null;
l2 = l1.get(level2);
String l3 = l2.get(level3);
return l3;
}
}
(Code untested)
You can create classes witch will hold the data structure
public class A {
Map<String, List<String>> map;
}
public class B {
Map<String, A> map;
}
Map<String, B> tagTree;
Use a Map of 3-Tuples:
class Tuple3<A,B,C> {
private A a;
private B b;
private C c;
// getters, setters, constructor
// make sure equals() and hashCode() are okay
}
Note, however, that the Map of Map of Maps can tell you in O(1) whether there are entries for some element by just looking in the outer map. Whereas, with the tuple solution, you can only work with full keys.
I think there is no reason for refactor this Map structure. But if possible, it is probably a good idea to encapsulate this Map in another class and give other developers a clean interface.
...
public void addTag(String language, String status, String tag)
public void removeTag(String language, String status, String tag)
public List<String> getTags(String language, String status)
...
I like most of the solutions suggested above. I think the simpler and efficient the design is - more supportable it will be.
Hence, I used basics - plain object composition to refactor your code.
package design;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class JavaTag{
private String tags;
JavaTag(String tags){
this.tags = tags;
}
}
class JavaTagStatusList{
private ArrayList<JavaTag> tagList = new ArrayList<JavaTag>();
JavaTagStatusList(){
}
public void addJavaTag (JavaTag tagObj){
if (tagObj != null){
tagList.add(tagObj);
}
}
}
class JavaTagStatusMap {
private HashMap<String, JavaTagStatusList> tagStatusMap = new HashMap<String, JavaTagStatusList>();
JavaTagStatusMap(){
}
public void addTagStatusEntry(String status, JavaTag obj){
if (tagStatusMap.containsKey(status)){
tagStatusMap.get(status).addJavaTag(obj);
}
else {
JavaTagStatusList statusList = new JavaTagStatusList();
statusList.addJavaTag(obj);
tagStatusMap.put(status, statusList);
}
}
}
Main:
public class MapofMapRefactor {
public static void main(String[] args) {
JavaTag tag1 = new JavaTag("Java-OOP");
JavaTag tag2 = new JavaTag("Java-Variables");
JavaTagStatusMap statusMap = new JavaTagStatusMap();
statusMap.addTagStatusEntry("Active", tag1);
statusMap.addTagStatusEntry("Active", tag2);
// HashMap of Java Lang Map
HashMap<String, JavaTagStatusMap> javaLanguageMap = new HashMap<String, JavaTagStatusMap>();
javaLanguageMap.put("Java", statusMap);
}
}
I have a little "Object":
Map<Integer, Map<WeekDay, Map<String, Data>>> obj
and I want to Map it to:
Map<Integer, Map<WeekDay, Map<String, DataDto>>> returnObj
how can I achive this?
The way I wanted to use was this one:
map(schedule, Map<Integer.class, Map<WeekDay.class, Map<String.class, DataDto.class>>>);
but at the "Map" I am stuck, becuase I can't add a .class behind them and in this state it doesn't work...
I would suggest to simplify your Map if possible:
class A {
WeekDay weekDay;
String str;
Data obj;
}
Map<Integer, A> map = ...;
Iterables.transform(map.values(), new Function<Data, DataDto>() {
#Override
public Object apply(String input) {
return ...;
}
});
or you can put it inside your class:
class Dictionary {
Map<Integer, Map<WeekDay, Map<String, Data>>> obj;
getDataDto(Integer key, Weekday weekDay, String str) {
final Data data = obj.get(key).get(weekDay).get(str);
return (new Function<Data, DataDto>() {
...
}).apply(data);
}
}
Think about operations you are going to use over your data structure and come up with the proper class. Your nested map doesn't look okay.
I am struggling to find a way to dispatch this to functions in java8
Person p = registry.getPerson();
if (field == Field.LASTNAME) {
p.setLastName(str);
}
if (field == Field.FIRSTNAME) {
p.setFirstName(str);
}
if (field == Field.MIDDLENAME) {
p.setMiddleName(str);
}
My idea is to use some kind of function dispatch table to replace the if statements in the case of more cases:
Map<Integer, Function> map = new HashMap<Integer, Function>
static {
map.put(1, new Function<String, String>() {
#Override
public Object apply(String str) {
person.setLastName(str);
return str;
}
}
}
But the code cannot compile, because i need to pass the person object some place. Anyone knows a pattern for this?
Assuming Field is an enum, you can add BiConsumer<Person,String> as an enum field:
class Person {
static enum Field {
FIRSTNAME(Person::setFirstName),
MIDDLENAME(Person::setMiddleName),
LASTNAME(Person::setLastName)
;
private BiConsumer<Person, String> setter;
private Field(BiConsumer<Person, String> setter) {
this.setter = setter;
}
}
public void set(Field field, String str) {
field.setter.accept(this, str);
}
......
}
Instead of storing Function<String,String>, you can store BiFunction<Person,String,String> and pass the Person instance in as a parameter.
Map<Integer, BiFunction<Person,String,String>> map =
new HashMap<Integer, BiFunction<Person,String,String>>();
static {
map.put(1, (person, str)->person.setLastName(str));
}
In the interest of simplicity, you could also just store a List of the functions, if you're just going to index them by an integer, it's faster for random access and makes for less complicated generic code:
List<BiFunction<Person,String,String>> list = new ArrayList<BiFunction<Person,String,String>>();
static {
list.add((person, str)->person.setLastName(str));
}