Map string list string in java

Convert a list of strings to a list of maps using Java streams

Each entry in the above list a map with keys as name and age and values as their corresponding values. This is what I have done to achieve the result.

listOfStrings.stream() .map(record -> Arrays.asList(record.split(",")).stream().map(field -> field.split(" mt24 mb12">
    javajava-8java-stream
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this question" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="question" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="1" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f4.0%2f" data-se-share-sheet-license-name="CC BY-SA 4.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this question
)">edited Aug 14, 2018 at 7:39
user9455968
asked Aug 14, 2018 at 7:34
15
    When you really do Arrays.asList(test.split(";")); there is no point of using Java streams, its all in memory already and you can iterate the array and build a map manually
    – user39950
    Aug 14, 2018 at 7:39
    why would you use a map for this? a map implies a key, an age is not a key. further more, why using age? why not using a birthDate?
    – Stultuske
    Aug 14, 2018 at 7:40
    @Stultuske, I meant to say that the string name would be a key and the string age would another key.
    – Ravi
    Aug 14, 2018 at 7:43
    @Ravi sounds like you don't know what a key is, or how it works. one value is a key (has to be unique, neither name nor age would be unique) the other is 'value'
    – Stultuske
    Aug 14, 2018 at 7:44
    2
    @user39950 Even when completely in-memory is often easier and more readable to write Stream code than explicit loops. For one: an explicit loop can potentially do anything, which means it can also contain any kind of bug. Stream operations are well-known and well defined, so by looking at the operations you already have a very good idea at what is happening. With a loop you have to look at the whole loop, decode every single line and ensure that nothing fancy happens, and only afterwards you have a good idea at what it does.
    – Giacomo Alzetta
    Aug 14, 2018 at 7:44
|Show 10 more comments

2 Answers 2

Reset to default
4

Here is another alternative using pattern matching, not as fast as a for loop but much faster than the original stream solution in my measurements.

public static void main(String[] args) < String test ="name=john,age=28;name=paul,age=30;name=adam,age=50"; String patternString = "(name)=(\\w*),(age)=(\\d*)[;]?"; Pattern pattern = Pattern.compile(patternString); Matcher matcher = pattern.matcher(test); List> list = new ArrayList<>(); while (matcher.find()) < Mapmap = new HashMap<>(); map.put(matcher.group(1), matcher.group(2)); map.put(matcher.group(3), matcher.group(4)); list.add(map); > >

A slight performance improvement could be had by not matching against the keys (name & age) and instead hardcoding them when creating the map elements.

Источник

List of Map.Entry [closed]

@AnujVictor You got like 5 guys asking you what you need. Just type it in the question. "WHAT I WANT": xyz.

2 Answers 2

what's you mean ?? you want to convert map element( key=value) to string value . for this, you can use a loop on map entry set and read key and value of map elements and create custom string and concat all list:

String resultString ="" ; for(Map.Entry entry : map.EntrySet()) < String key = entry.getKey(); String value = entry.getValue(); // create custom string for each map element String testString = key + " mt24">
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this answer
answered Apr 3, 2017 at 6:22
8
    thanx man it worked, but what if i want to add it in an String array as a key value pair?
    – Anuj Victor
    Apr 3, 2017 at 6:30
    1
    Hint: string concatination is a loop is not a good (performant) idea. Use a StringBuilder instead
    – Stefan Warminski
    Apr 3, 2017 at 6:30
    1
    @AnujVictor You can add the created string to a list and convert the list after your loop String[] entries = entryList.toArray(new String[entryList.size()]);
    – Stefan Warminski
    Apr 3, 2017 at 6:34
    @StefanWarminski actually its a List so i guess cant be converted, its throughing java.lang.ArrayStoreException
    – Anuj Victor
    Apr 3, 2017 at 6:39
    @M2E67 instead of concatenating to a String is it possible to add it in a String array?
    – Anuj Victor
    Apr 3, 2017 at 6:43
|Show 3 more comments
0

Just as an answer to your comment: I just tried it and there is no exception at all:

Map map = new LinkedHashMap<>(); map.put("AREA_DS_ID", "1,5,9,13,17,21,25,29,33"); map.put("PROJECTS_ID", "13,78,267,18,28,33,55,99"); map.put("SIGNAL_NAME", "a"); map.put("ASSESSMENTNAME", "a"); List entryList = new ArrayList<>(); StringBuilder sb = new StringBuilder(); for (Entry entry : map.entrySet()) < String value = entry.getKey() + '=' + entry.getValue(); entryList.add(value); sb.append(value); >String[] entries = entryList.toArray(new String[entryList.size()]); String mapAsString = sb.toString();

Источник

How to convert a Map> to Map> using forEach operation

I am wondering how can I do it using forEach in Java 8. Also, with the forEach lambda, will it be any better with the code performance?

3 Answers 3

will it be any better with the code performance?

No, it'll not. Iterative solutions are usually more performant.

how can I do it using forEach

There's a special operation collect() in the Stream API that is meant to populate a mutable container (e.g. Collection , StringBuilder , etc.) with the contents of the stream pipeline. Usage of forEach() for that purpose is highly discouraged by the documentation. Consider utilizing forEach() only as a last resort, when there's no other way to achieve that.

To do that with collect() , first, you need to create a stream of entries.

Based on each entry, a new entry has to be created, map() operation is utilized for that purpose. Static method Map.entry() is used to instantiate a new entry.

And then apply the terminal operation collect() by passing Collectors.toMap() as parameter, which creates a collector (object responsible for placing the stream elements into a mutable container, a map in this case) based on the two provided functions (for keys and values).

public static void main(String[] args) < Map> mapWithList = Map.of("1", List.of("1", "2", "3")); Map> result = mapWithList.entrySet().stream() .map(entry -> Map.entry(entry.getKey(), new HashSet<>(entry.getValue()))) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); System.out.println(result); > 

Источник

How to add Map into Map> in java

You can't. Probably best to create a custom object that holds both your patient list and the date, and use that instead of the map. You could declare your map to be of type Map but that approach is a bit questionable.

4 Answers 4

You are trying to place a string where a map expects a List.

patientMap.put("PATIENTLIST", patientList); patientMap.put("LASTKEY", date); 
patientMap.put(date, patientList); 

With a map where date string is key and list of patient is value you can quickly get a list of patients for a given date.

If you want to use a map to hold a date and list of objects in string form, then you would have to convert back those strings back to their original date or list of patient objects.

If this is really what you want I suggest you look into java object serialization and deserialization.

That looks like a signature or a serialized version of an object that has 2 Properties: LASTKEY and PATIENTLIST. Similar to what Robby Cornelissen suggested in the other answer.

Are you sure the method you provided is the place where you expect an object you described? Why is your method signature like public Map> ?

Here are the small changes which you can do to achieve above (Definitely you have to change the return type):

public Map getPatients(String sendingApplication,String sendingFacility) < // TODO Auto-generated method stub MappatientMap = null; List patientList = null; patientMap = new HashMap(); patientList = new ArrayList(); try < PatientInfoDAO patientInfoDAO = new PatientInfoDAOImpl(); ItemCollectionitems = patientInfoDAO.getPatients(sendingApplication, sendingFacility); for(Item item : items) < PatientInfo patient = new PatientInfo(); patient.setAdministrativeSex("Male"); patientList.add(patient); >String date = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); PatientMapObject pmo = new PatientMapObject(); pmo.setPatientList(patientList); pmo.setPDate(date); patientMap.put("PATIENTLIST", pmo); return patientMap; >catch(Exception ase) < throw new RuntimeException("internalServerError"); >> class PatientMapObject < private ListpatientList; private String pdate; public void setPDate(String pdate) < this.pdate = pdate; >public void setPatientList(List patientList) < this.patientList = patientList; >//getters > 

You can only add the defined type of object in Map 's definition (i.e List because you are creating map like Map ) to add String also you should use Map

Источник

Читайте также:  How to submit with javascript
Оцените статью