Mapping Two String Arrays in Java - java

I'm trying to find out if there is an easier way to map two string arrays in Java. I know in Python, it's pretty easy in two lines code. However, i'm not sure if Java provides an easier option than looping through both string arrays.
String [] words = {"cat","dog", "rat", "pet", "bat"};
String [] numbers = {"1","2", "3", "4", "5"};
My goal is the string "1" from numbers to be associated with the string "cat" from words, the string "2" associated with the string "dog" and so on.
Each string array will have the same number of elements.
If i have a random given string "rat" for example, i would like to return the number 3, which is the mapping integer from the corresponding string array.
Something like a dictionary or a list. Any thoughts would be appreciated.

What you need is a Map in java.
Sample Usage of Map :
Map<String,String> data = new HashMap<String,String>();
` for(int i=0;i<words.length;i++) {
data.put(words[i],numbers[i]);
}
For more details please refer to https://docs.oracle.com/javase/tutorial/collections/interfaces/map.html

Oracle Docs for HashMap
import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
String[] words = {"cat","dog", "rat", "pet", "bat"};
String[] numbers = {"1","2", "3", "4", "5"};
Map<String,String> keyval = new HashMap<String,String>();
for(int i = 0 ; i < words.length ; i++ ){
keyval.put(words[i], numbers[i]);
}
String searchKey = "rat";
if(keyval.containsKey(searchKey)){
System.out.println(keyval.get(searchKey));
}
}
}

Related

Split a string in an Arraylist in Java into substring of letters

I have two classes Reader and Tokenizer. I want to split Strings in Wlist Arraylist from the Reader class in tokenizer class. Splitting must be done based on odd and even length of the String.
Ex: If string is "teacher", as its length is odd it should be split into three parts "te", "ac", "her".
If string is even like "cattle" it should be split in 3 parts "ca", "tt", "le".
Reader Class
import java.util.ArrayList;
import java.util.List;
public class Reader {
String[] wordList = {"Printer", "Airport", "Painter", "Letter",
"vehicle", "Teacher"};
String[] SentenceList = {"Device made to waste ink and paper","Platform for Commercial air transport",
"Someone who uses colors and brushes","a written type of communication sent by mail",
"Thing used to travel via land","A person who teaches"};
ArrayList<String> Wlist = new ArrayList<>(6);
public ArrayList<String> wordCheck(){
for(int i=0;i<6;i++){
if((wordList[i] != null) && (!wordList[i].equals("")) && (wordList[i].matches("^[a-zA-Z]*$"))
&& (wordList[i].length()>4)) {
//System.out.println("Array does satisfy the required criteria");
Wlist.add(wordList[i].toUpperCase());
}
else
{
System.out.println("Array does NOT satisfy the required criteria");
break;
}
}
//System.out.println(Wlist);
return Wlist;
}
public ArrayList<String> getWord(){
return wordCheck();
}
public ArrayList<String> Sentence(){
ArrayList<String> Slist = new ArrayList<>(6);
for(int i=0;i<6;i++){
Slist.add(SentenceList[i]);
}
//System.out.println(Slist);
return Slist;
}
}
// This is the updated Tokenizer class
import java.util.ArrayList;
import java.util.List;
public class Tokenizer {
Reader rd = new Reader();
ArrayList<String> SplList = new ArrayList<>();
public ArrayList<String> splitString() {
ArrayList<String> Wlist = rd.getWord();
//String[] result = new String[(Wlist.get().length()+2)/3];
for(int i=0;i<Wlist.size();i++){
SplList.add(Arrays.toString(Wlist.get(i).split("(?<=\\\\G..)(?=..)")));
}
System.out.println(SplList);
return SplList;
}
}
If you're asking how to split a string into pairs of letters, with any remainder left with the last split:
String[] parts = str.split("(?<=\\G..)(?=..)");
which achieves your goal (see below).
The split matches between these two look arounds:
(?<=\\G..) two chars after the end of the last match
(?=..) there are (at least) two chars after
String[] wordList = {"Printer", "Airport", "Painter", "Letter", "vehicle", "Teacher"};
List<String[]> splitWords = Arrays.stream(wordList).map(s -> s.split("(?<=\\G..)(?=..)")).collect(toList());
splitWords.forEach(a -> System.out.println(Arrays.toString(a)));
Output:
[Pr, in, ter]
[Ai, rp, ort]
[Pa, in, ter]
[Le, tt, er]
[ve, hi, cle]
[Te, ac, her]

How can I find out if an arraylist is missing one and only one element from an array?

I have a String arraylist called 'hand' that takes random elements from 3 different String arrays, PEOPLE, WEAPONS AND ROOMS. Is there any way I can determine if the arraylist has all but one element from each category? So if 'hand' contains 8 of the 9 Strings in the String array ROOMS, it will return the string that it doesn't have for that array? This method should only apply if 'hand' is missing EXACTLY 1 element from the specified array. If it's missing more than one element from a specified array, it shouldn't do anything.
import java.util.ArrayList;
import java.util.List;
public class Main {
public List<String> hand = new ArrayList<String>();
public final static String[] PEOPLE = new String[] {
"Miss. Scarlet",
"Mrs. Peacock",
"Colonel Mustard",
"Professor Plum",
"Mrs. White",
"Mr. Green"
};
public final static String[] WEAPONS = new String[] {
"Wrench",
"Candlestick",
"Pipe",
"Rope",
"Revolver",
"Knife"
};
public final static String[] ROOMS = new String[] {
"Library",
"Kitchen",
"Study",
"Conservatory",
"Ballroom",
"Lounge",
"Hall",
"Billiard Room",
"Dining Room"
};
public Main() {
hand.add("Library");
hand.add("Lounge");
hand.add("Wrench");
hand.add("Miss. Scarlet");
hand.add("Mrs. Peacock");
hand.add("Colonel Mustard");
hand.add("Professor Plum");
hand.add("Mrs. White");
}
public static void main(String[] args) {
Main main = new Main();
}
}
I guess this is what you're looking for: use removeAll() method on a List.
So, convert your arrays to List with Arrays.asList(..).
Than removeAll hands collection from each of your former arrays. If the size of the remaining List is 1 - this is what you are looking for.
List<String> peoples = new ArrayList<>(Arrays.asList(PEOPLE));
peoples.removeAll(hands);
if (peoples.size() == 1)
{
// here your hands List contained all items from PEOPLE, except 1
}
Declare a method that takes two parameters : the constant list and your hand and that will return a String : the missing String element in your hand if it is the last one missing or else null.
Call this method three times by passing at each time your hand and one of the three constant lists.
That's all.
In code it could give :
public String findLastMissingElement(String[] constants, List<String> hand){
String missingElement = null;
for (String constant : constants){
if (!hand.contains(constant) && missingElement==null){
missingElement = constant;
}
else if (!hand.contains(constant)){
return null;
}
}
return missingElement;
}
And you could call it in this way :
String missingPeople = findLastMissingElement(PEOPLE, hand);
String missingWeapon = findLastMissingElement(WEAPONS, hand);
String missingRoom = findLastMissingElement(ROOMS, hand);

One-liner to count number of occurrences of String in a String[] in Java?

I have an array of String:
String[] myArray = {"A", "B", "B", "C"};
Is there a quick way to count the number of occurrences of a string in that array? Yes, I know I can iterate and do the count myself:
int count = 0;
String whatToFind = "B";
for (String s : myArray) {
if (s.equals(whatToFind)) {
++count;
}
}
But I was wondering if there was a utility function for this. I couldn't find anything in Arrays or ArrayUtils. Is it possible to do this with a one-liner?
You can use the frequency method:
List<String> list = Arrays.asList(myArray);
int count = Collections.frequency(list, "B");
or in one line:
int count = Collections.frequency(Arrays.asList(myArray), "B");
With Java 8 you can also write:
long count = Arrays.stream(myArray).filter(s -> "B".equals(s)).count();
Or with a method reference:
long count = Arrays.stream(myArray).filter("B"::equals).count();
You can also try using Guava which is full of useful utilities. Using below code, you can count the frequency via Multiset:
public static void main(final String[] args) {
String[] myArray = {"A", "B", "B", "C"};
Multiset<String> wordsMultiset = HashMultiset.create();
wordsMultiset.addAll(new ArrayList<String>(Arrays.asList(myArray)));
int counts=wordsMultiset.count("B");
System.out.println(counts);
}
Although I know that you are looking for a single liner, but Guava is full of many more utils which are not possible with routine java utils.

Store associative array of strings with length as keys

I have this input:
5
it
your
reality
real
our
First line is number of strings comming after. And i should store it this way (pseudocode):
associative_array = [ 2 => ['it'], 3 => ['our'], 4 => ['real', 'your'], 7 => ['reality']]
As you can see the keys of associative array are the length of strings stored in inner array.
So how can i do this in java ? I came from php world, so if you will compare it with php, it will be very well.
MultiMap<Integer, String> m = new MultiHashMap<Integer, String>();
for(String item : originalCollection) {
m.put(item.length(), item);
}
djechlin already posted a better version, but here's a complete standalone example using just JDK classes:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class Main {
public static void main(String[] args) throws Exception{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String firstLine = reader.readLine();
int numOfRowsToFollow = Integer.parseInt(firstLine);
Map<Integer,Set<String>> stringsByLength = new HashMap<>(numOfRowsToFollow); //worst-case size
for (int i=0; i<numOfRowsToFollow; i++) {
String line = reader.readLine();
int length = line.length();
Set<String> alreadyUnderThatLength = stringsByLength.get(length); //int boxed to Integer
if (alreadyUnderThatLength==null) {
alreadyUnderThatLength = new HashSet<>();
stringsByLength.put(length, alreadyUnderThatLength);
}
alreadyUnderThatLength.add(line);
}
System.out.println("results: "+stringsByLength);
}
}
its output looks like this:
3
bob
bart
brett
results: {4=[bart], 5=[brett], 3=[bob]}
Java doesn't have associative arrays. But it does have Hashmaps, which mostly accomplishes the same goal. In your case, you can have multiple values for any given key. So what you could do is make each entry in the Hashmap an array or a collection of some kind. ArrayList is a likely choice. That is:
Hashmap<Integer,ArrayList<String>> words=new HashMap<Integer,ArrayList<String>>();
I'm not going to go through the code to read your list from a file or whatever, that's a different question. But just to give you the idea of how the structure would work, suppose we could hard-code the list. We could do it something like this:
ArrayList<String> set=new ArrayList<String)();
set.add("it");
words.put(Integer.valueOf(2), set);
set.clear();
set.add("your");
set.add("real");
words.put(Integer.valueOf(4), set);
Etc.
In practice, you probably would regularly be adding words to an existing set. I often do that like this:
void addWord(String word)
{
Integer key=Integer.valueOf(word.length());
ArrayList<String> set=words.get(key);
if (set==null)
{
set=new ArrayList<String>();
words.put(key,set);
}
// either way we now have a set
set.add(word);
}
Side note: I often see programmers end a block like this by putting "set" back into the Hashmap, i.e. "words.put(key,set)" at the end. This is unnecessary: it's already there. When you get "set" from the Hashmap, you're getting a reference, not a copy, so any updates you make are just "there", you don't have to put it back.
Disclaimer: This code is off the top of my head. No warranties expressed or implied. I haven't written any Java in a while so I may have syntax errors or wrong function names. :-)
As your key appears to be small integer, you could use a list of lists. In this case the simplest solution is to use a MultiMap like
Map<Integer, Set<String>> stringByLength = new LinkedHashMap<>();
for(String s: strings) {
Integer len = s.length();
Set<String> set = stringByLength.get(s);
if(set == null)
stringsByLength.put(len, set = new LinkedHashSet<>());
set.add(s);
}
private HashMap<Integer, List<String>> map = new HashMap<Integer, List<String>>();
void addStringToMap(String s) {
int length = s.length();
if (map.get(length) == null) {
map.put(length, new ArrayList<String>());
}
map.get(length).add(s);
}

Java split string from array

I have a string array that contains some information.
Example:
String [] testStringArray;
testStringArray[0]= Jim,35
Alex,45
Mark,21
testStringArray[1]= Ana,18
Megan,44
This is exactly how the information is. Now my problem is I want to make each element a seperate element in an array and I want to split it based on the \n character.
So I want
newArray[0]=Jim,35
newArray[1]=Alex,45
newArray[2]=Mark,21
newArray[3]=Ana,18
etc etc. I am aware of the split method but won't this just split each array element into a completely new array instead of combining them?
If anyone could help, it would be appreciated. Thanks
Something like this:
// Splits the given array of Strings on the given regex and returns
// the result in a single array.
public static String[] splitContent(String regex, String... input) {
List<String> list = new ArrayList<>();
for (String str : input) {
for (String split : str.split(regex)) {
list.add(split);
}
}
return list.toArray(new String[list.size()]);
}
you can call it this way:
String[] testStringArray = ...;
String[] newArray = splitContent("\n", testStringArray);
Because of the use of varargs you can also call it like this:
String[] newArray = splitContent("\n", str1, str2, str3, str4);
where strX are String variables. You can use any amount you want. So either pass an array of Strings, or any amount of Strings you like.
If you don't need the old array anymore, you can also use it like this:
String[] yourArray = ...;
yourArray = splitContent("\n", yourArray);
String[] testStringArray = new String[2];
ArrayList<String> result = new ArrayList<String>();
testStringArray[0]= "Jim,35\nAlex,45\nMark,21";
testStringArray[1]= "Jiam,35\nAleax,45\nMarak,21";
for(String s : testStringArray) {
String[] temp = s.split("\n");
for(String t : temp) {
result.add(t);
}
}
String[] res = result.toArray(new String[result.size()]);
Try This is working Code >>
String[] testStringArray = new String[2]; // size of array
ArrayList<String> result = new ArrayList<String>();
testStringArray[0]= "Jim,35\nAlex,45\nMark,21"; // store value
testStringArray[1]= "Ana,18\nMegan,44";
for(String s : testStringArray) {
String[] temp = s.split("\n"); // split from \n
for(String t : temp) {
result.add(t); // add value in result
System.out.print(t);
}
}
result.toArray(new String[result.size()]);
you can first merge the strings into one string and then use the split method for the merged string.
testStringArray[0]= Jim,35
Alex,45
Mark,21
testStringArray[1]= Ana,18
Megan,44
StringBuffer sb = new StringBuffer();
for(String s : testStringArray){
s = s.trim();
sb.append(s);
if (!s.endWith("\n")){
sb.append("\n");
}
}
String[] array = sb.toString().split("\n");
Try this. It is simple and readable.
ArrayList<String> newArray = new ArrayList<String>();
for (String s : testStringArray) {
newArray.addAll(Arrays.asList(s.split("\\n"));
}
Firstly, you can't write what you just did. You made a String array, which can only contain Strings. Furthermore the String has to be in markers "" like "some text here".
Furthermore, there can only be ONE String at one place in the array like:
newArray[0] = "Jim";
newArray[1] = "Alex";
And NOT like:
newArray[0] = Jim;
And CERTAINLY NOT like:
// Here you're trying to put 2 things in 1 place in the array-index
newArray[0] = Jim, 35;
If you wan't to combine 2 things, like an name and age you have to use 2D array - or probably better in your case ArrayList.
Make a new class with following object:
public class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
And afterwards go to your class where you want to use the original array, and write:
ArrayList<Person> someNameOfTheArrayList = new ArrayList<Person>();
someNameOfTheArrayList.add(new Person("Jim", 32));
someNameOfTheArrayList.add(new Person("Alex", 22));

Categories