• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Merge two arrays

 
Hui Zhao
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Suppose a1 and a2 are two dimensional arrays

My goal is to append the second row according to the first row's matchness.
Finally if
merge the first row of a1 and a2 should get


I have three days but no achievement.
Here is the code.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider how you could use a Map (for your purposes, a java.util.LinkedHashMap would be a wise choice) to store the relationship between the first and second strings. Since a Map automatically eliminates duplicate keys, and since LinkedHashMap stores the keys in insertion order, it would do virtually all of the work for you. You'd just add all the pairs, allocate new arrays the same size as the map, then iterate over the map and populate the two arrays.
 
Hui Zhao
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am not familiar with using Map skills.
Would you please provide me a piece of code?

Thanks
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This should be a fun introduction to the Collections family. See the JavaDoc for Map. Some of the methods you'll want to use:

The key-value pairs will come back in a Set of MapEntry objects. Look up the doc for Set, find iterator() and follow the links on Iterator. You can get MapEntry objects with that, and then get all the keys and values from there.

Any time you get stuck, Google for "java map example" or something like that. Start up some code and show us what you make. We can really help you best when you have code that almost works.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic