Extract a fields data from a Map<Integer, Object> into a String - java

I have an Customer Object like below.
public class Custoemr {
private String Id;
Private String Name;
Private String Address;
Private String Description;
Setter/Getter;
toString;
}
This is Contained in Map<String, Customer> map, which contains the customerId and Object as key and value respectively. For analysis purposes, I need to collect all the customer description data in String to be written in a file.
To do that I need to Extract data from description in String and not List<String>.
I saw several examples on the internet which collects them as a List<String> but I need it in a single String.
Is there a way to extract the information without iterating I mean by using java Streams.

If I understood correctly:
yourMap.values()
.stream()
.map(Customer::getDescription)
.collect(Collectors.joining(","));

Related

Java Stream: How to map multiple value to a single DTO?

I have a List result in my Spring Boot service method as shown below:
Country:
String name;
List<State> states;
State:
String name;
Long population;
List<Town> towns;
Town:
String name;
I return Country list from my repository and it has all the related State and Town date for each Country. I want to map this data to a DTO as shown below:
public class CountryDTO {
private Long id;
private String name;
private Long population; //population sum of states by country
private List<Town> towns;
//constructor
}
So, how can I map my Country entity to this CountryDTO properly as explained above? I need the following data:
Country name
Sum of population by each country
Towns of each country
Update: Here is my service method where I tried to use Java Stream and then also ModelMapper, but cannot return desired values :(
List<CountryDTO> countries = countryRepository.findAll().stream()
.flatMap(x -> x.getStates().stream())
.map(x -> new CountryDTO(x.getCountry(), <-- need to return sum of population here -->, ObjectMapperUtils.mapAll(x.getTowns(), TownDTO.class)))
.toList();
You can use Stream#mapToInt to get all the state populations and .sum to add them up.
Stream#flatMap can be used to get all the towns of each state into a single stream.
List<CountryDTO> res = countries.stream().map(c -> new CountryDTO(c.getName(),
c.getStates().stream().mapToInt(State::getPopulation).sum(),
c.getStates().stream().flatMap(s -> s.getTowns().stream()).toList())).toList();
Didn't get your question completely, maybe it will be more helpful if you share the exact response returned by the APIs.
But, going by the use case, if you are getting a list in the response, you always have the option of stream the list, iterate each element, and then use conditional / grouping logics to get the data in the desired way.
For example;
Let's say, you have a list of Object type, for which you have a repository layer configured as ObjetRepo. Now, if you are getting a list of objects, you can stream it like this:
#Autowired
private ObjectRepo objectRepo;
public List<Object> method() {
List<Object> objects = new ArrayList<>();
objectRepo.findAll().forEach(objects::add);
// Here, instead of add, any other logic can be used.
// You can also write a method, and use that method here
// objectRepo.findAll().forEach(objects::someMethod);
return objects;
}
Hope this helps.

How to match lists of two objects based on a common field using map?

Class AccountInfo
{
String id;
String name;
String type;
}
Class MeetingsInfo
{
String id;
String count;
Date meetingDate;
}
List<AccountInfo> accounts;
List<MeetingsInfo> meetings;
Here "accounts" contain details of all accounts and meetings contain all meetings of that day. How to create a new list of "AccountInfo" which contain "id" same as the "id" of meetings using "map" function?
I tried to do it this way:
List<AccountInfo> newAccounts = accounts.stream().map(meetings::getAccountId);
Please do mention if there is any optimised method than using map.
create a new list of "AccountInfo" which contain "id" same as the "id" of >meetings
What do want to do if id's are same, merge in a new variable ?

JAVA - Reading CSV file based on another CSV file

I am struggling with making this work properly. So I have two CSV Files.
And this One
So the main thing is. I have SearchTerms in 2nd CSV. In first CSV I have SearchTerms also, which should work as a "tag".
What I need is to get product ids from first CSV saved to a List < String > based on, what searchterm from 2nd csv is used. So when Akt (pan) is used, one set of List of IDS is exported. If there is more Akt (pan) sets of ids, they are saved to one list as array I guess.
I tried to read it with CSVloaders and searching it with lookup() method
private final Map<List<String>, Comparison> data = Maps.newHashMap();
public Comparison lookup(String searchTerm) {
return data.get(searchTerm);
}
Where Comparison Class is
public class Comparison {
#Parsed(field = "ProductId1")
private String productId1;
#Parsed(field = "ProductId2")
private String productId2;
#Parsed(field = "ProductId3")
private String productId3;
#Parsed(field = "SearchTerm")
private String SearchTerm;
public String getProductId1() {
return productId1;
}
public String getProductId2(){
return productId2;
}
public String getProductId3(){
return productId3;
}
public List<String> getProductIds(){
List<String> ids = new ArrayList<>();
Collections.addAll(ids, productId1, productId2, productId3);
return ids;
}
}
My solution was bad. I was getting NullPointerException constantly whenever I tried to use lookup() method.
Do you have any ideas how to make this work? Thank oyu
Problem is with the data type of key in your HashMap. It should be a string as per your data, not a List<>.
private final Map<String, Comparison> data = Maps.newHashMap();
public Comparison lookup(String searchTerm) {
return data.get(searchTerm);
}
Then the returning object(typed Comparison) would have the all products Ids for the given search Term.

Returning all the keys from a HashMap withou looping

I am attemping to populate a JComboBox with the names of cities.
My program has a class called 'Country'. The Country object contains a HashMap of objects called 'City' with a method getName, returning a String value.
public class Country {
private final Map<String, City> cities = new HashMap<>();
public Collection<City> getCities() {
return cities.values();
}
}
public class City {
String cityName;
public String getName() {
return cityName;
}
}
Is it possible to return an String array of cityName without using a loop? I was trying the following but it did not work:
Country country 1 = new Country();
String[] cityNames = country1.getCities().toArray();
JComboBox cityChoice = new JComboBox(cityNames);
This returns an Array of City objects, however I am not sure how to use the City getName method in conjunction with this.
You can not avoid looping. Either, you will loop, or Java will loop in the background.
You can avoid writing your own loop if keys in your map are city names. Then, you could only ask .keySet() from the map. But, even in that case, Java would loop in the background and copy the keys.
Other way is that you loop, but hide the loop in some method (lets say getCitiesArray()) in the class. So, you could do country1.getCitiesArray(); in the calling method. Code would look better and be easier to read, but you would still need to have loop inside of the class.
You can store Map key as CityName then do below to get Names.
cities.keySet();
The city object can be used directly in the combobox with some minor alterations.
public class City {
String cityName;
public String getName() {
return cityName;
}
#Override
public String toString() {
return getName();
}
}
Then the population code
Country country1 = new Country();
City[] cities = country1.getCities().toArray();
JComboBox<City> cityChoice = new JComboBox<City>(cities);
You should probably override hashCode and equals also.
If you are using Java 8, you can use the Stream API to map the names of the cities to a String:
String []cityNames = country1.getCities().stream().map(City::getName).toArray(String[]::new);

convert fetched data into string , string array map

i am fetching a data from sqlite in android which is as follows
URL PHONE
---------------------------------
/test/img1.png 98989898
/test/img1.png 61216121
/test/img2.png 75757575
/test/img2.png 40404040
/test/img3.png 36363636
now i want to create such a map which stores the data as follows
/test/img1.png [98989898 , 61216121 ]
/test/img2.png [75757575 , 40404040 ]
/test/img3.png [36363636]
so that i can pass the whole map to the function which function eventually in background pick up the image url and send the data to the arrays listed to the phone number. so how can i transform the data that i have fetched into the key to string array style ?
I'd create a Map<String, List<String>> (aka "multi-map"). You don't have to know how many phone numbers for a given URL before you start if you use List<String>. That's not so if you choose the array route.
Map<String, List<String>> results = new HashMap<String, List<String>>();
while (rs.next()) {
String url = rs.getString(1);
String phone = rs.getString(2);
List<String> phones = (results.contains(url) ? results.get(url) : new ArrayList<String>());
phones.add(phone);
results.put(url, phones);
}
Google Collections has a multi-map that you can use out of the box, but I think you'll agree that this is sufficient.
If you want to store more items (e.g. name) you should start thinking about an object that encapsulates all of them together into one coherent thing. Java's an object-oriented language. You sound like you're guilty of thinking at too low a level. Strings, primitives, and data structures are building blocks for objects. Perhaps you need a Person here:
package model;
public class Person {
private String name;
private Map<String, List<String>> contacts;
// need constructors and other methods. This one is key
public void addPhone(String url, String phone) {
List<String> phones = (this.contacts.contains(url) ? this.contacts.get(url) : new ArrayList<String>());
phones.add(phone);
this.contacts.put(url, phones);
}
}
I'll leave the rest for you.
If you go this way, you'll need to map a result set into a Person. But you should see the idea from the code I've posted.

Categories