How to retrieve word after specific word in Java? - java

I've this kind of String:
{aa=bbbb, cc=blabla1, ee=ffff, cc=blabla2, gg=hhhh, cc=blabla3,.......}
and i want to get a list of all words after cc=.
How can i do it? I'm not very confident with regex stuff.

public static void main(String[] args) {
String input = "aa=bbbb, cc=blabla1, ee=ffff, cc=blabla2, gg=hhhh, cc=blabla3";
String[] splitValues = input.split(", ");
Map<String,List<String>> results = new Hashtable<>();
List<String> valueList = null;
// iterate through each key=value adding to the results
for (String a : splitValues) {
// a = "aa=bbbb" etc
String[] keyValues = a.split("=");
// you can check if values exist. This assumes they do.
String key = keyValues[0];
String value = keyValues[1];
// if it is already in map, add to its value list
if (results.containsKey(key)) {
valueList = results.get(key);
valueList.add(value);
} else {
valueList = new ArrayList<>();
valueList.add(value);
results.put(key, valueList);
}
}
System.out.println("cc= values");
valueList = results.get("cc");
// assumes value is in results
for (String a : valueList)
System.out.println(a);
}

Your question is very vague but I am guessing the String is provided as is, like:
String toSearch = "{aa=bbbb, cc=blabla1, ee=ffff, cc=blabla2, gg=hhhh, cc=blabla3,.......}";
By list I am guessing you are referring to the abstract List object and not to an array. Here is a solution:
String toSearch = "{aa=bbbb, cc=blabla1, ee=ffff, cc=blabla2, gg=hhhh, cc=blabla3,.......}";
List<String> result = new ArrayList<String>();
int prevMatch = 0;
while (toSearch.indexOf("cc=", prevMatch+1) != -1) {
result.add(toSearch.substring( // Substring method.
toSearch.indexOf("cc=",prevMatch+1)+3,toSearch.indexOf(",") //Getting correct indexes.
));
prevMatch = toSearch.indexOf("cc=",prevMatch+1);
}
The prevMatch variable ensures that the indexOf("cc=") that will be returned will be the next one occurring in the String. For the above String the returning ArrayList will contain the words "blabla1","blabla2", "blabla3" and whatever else is encountered.

Related

Read text file line by line and store names into list in java

The task is to read the given file and return list of full names. I've separated the lines successfully and should be able to get both first and last names, but I'm a bit confused about how should I do that.
How am I able to get full names from readData()?
What I'm looking for is this output ["Alice Smith", "Bob Brown", "Carol White", "David Doe"] and not duplicated names.
My code looks like this so far:
public class GradeRepository {
public GradeRepository(){
readData();
}
public void readData() {
for (String line : readLines()) {
String[] parts = line.split("\\|");
String firstName = parts[0];
String lastName = parts[1];
String subject = parts[2];
String grade = parts[3];
System.out.println(firstName);
System.out.println(lastName);
System.out.println(subject);
System.out.println(grade);
System.out.println(Arrays.toString(parts));
}
}
public List<String> getFullNames() {
List<String> fullNames = new ArrayList<>();
return fullNames;
}
private List<String> readLines() {
try {
return Files.readAllLines(Paths.get("src/ex1/grades.txt"));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Given text file:
grades.txt
Alice|Smith|math|5
Bob|Brown|english|4
David|Doe|math|3
Bob|Brown|math|4
Bob|Brown|chemistry|5
Alice|Smith|english|4
Carol|White|chemistry|3
David|Doe|chemistry|4
readData needs to be modified either to return a list of String[] where each string array represents a line or a field List<String[]> data needs to be created in GradeRepository and populated in readData.
Next, to get rid of duplicate names a Set<String> should be used as suggested in the comments, and LinkedHashSet implementation allows to keep the insertion order.
Example implementation where readData returns a list:
public List<String[]> readData() {
List<String[]> data = new ArrayList<>();
for (String line : readLines()) {
String[] parts = line.split("\\|");
// ... print parts as above if necessary...
data.add(parts);
}
return data;
}
public Set<String> getFullNames() {
Set<String> fullNames = new LinkedHashSet<>();
for (String[] row : readData()) {
fullNames.add(row[0] + " " + row[1]);
}
return fullNames;
}
It may be more preferable to use Stream API to avoid creation of intermediate collections, so all these methods may be rewritten into one:
public Set<String> getFullNames() throws Exception {
return Files.lines(Path.of("dataset.txt")) // Stream<String>
.map(line -> line.split("\\|")) // Stream<String[]>
.filter(arr -> arr.length > 1) // ensure there are 2 columns at least
.map(arr -> arr[0] + " " + arr[1]) // Stream<String>
.collect(Collectors.toCollection(LinkedHashSet::new)); // get collection of unique names
}

Unable to get the List<Integer> output to Katalon Test case

I have been working to get the list of Arraylist output to Testcase
Here is my code(Keyword):
#Keyword
public List<Integer> othersites() {
String[] sits = new String[9];
sits[0] = "https://www.tadawul.com.sa/wps/portal/tadawul/home/";
sits[1] = "https://www.msm.gov.om/";
WebUI.navigateToUrl(sits[0]);
String tdwl = WebUI.getText(findTestObject('Object Repository/Sites/site_tdwl'),FailureHandling.CONTINUE_ON_FAILURE)
String[] parts0 = tdwl.split("\\.")
String part0 = parts0[0];
String part00 = Integer.parseInt(part0.replaceAll(",", ""))
//println part00
List<String> list = new ArrayList<String>();
list.add(part00);
List<Integer> newList1 = new ArrayList<Integer>(list.size()) ;
for (String myInt1 : list)
{
newList1.add(Integer.valueOf(myInt1));
}
return newList1
}
Katalon Test case:
def newList1 = [];
newList1 << CustomKeywords.'decypha_equities.otherSiteValuesCapture.othersites'();
println newList1[0];
I could get the whole Arraylist, but i need to access to array elements in my test case(not inside the keyword)?
my output:
[8056, 3997, 6547, 10295, 2890, 14908, 1551, 1801, 5114]
othersites() method is returning the whole list. And then you are assigning the result to a new list with newList1 << CustomKeywords.'decypha_equities.otherSiteValuesCapture.othersites'();.
Change your test case to this
def newestList = CustomKeywords.'decypha_equities.otherSiteValuesCapture.othersites'();
println newestList[0];
to access the first element of the list.

Input a name and a role and get an output of that role with the names

I need to do this for school. Its supposed to be a JAVA project.
So for example, if we give an input:
thomas teacher
charlie student
abe janitor
jenny teacher
The output will be:
teachers,thomas,jenny
students,charlie,
janitor,abe.
I am just a beginner so, so far I have this code:
`Scanner in = new Scanner(System.in);
String line = in.nextLine();
String[] words = line.split(" ");
//TreeMap treemap = new TreeMap();
ArrayList<String> admin = new ArrayList<String>();
Scanner input = new Scanner(System.in);
while(true){
Boolean s = input.nextLine().equals("Done");
//treemap.put(line, "admin");
if(words[1].contentEquals("admin")){
admin.add(words[0]);
}
else if(s == true){
break;
}
}
System.out.println("admins," + "," + admin);`
I was originally using a treemap but I don't know how to make it work so I thought of using an ArrayList and eliminating the brackets at the end.
EDIT:
So I now have the code:
HashMap<String, String> teacher = new HashMap<String, String>();
HashMap<String, String> student = new HashMap<String, String>();
HashMap<String, String> janitor = new HashMap<String, String>();
System.out.println("Enter a name followed by a role.");
Scanner in = new Scanner(System.in);
String line = in.nextLine();
Scanner name = new Scanner(System.in);
String r = name.nextLine();
while(true){
if(line.equals(r + " " + "teacher")){
teacher.put(r, "teacher");
}
}
I'll give you the hint because you should do it yourself.
Use a HashMap<String, List<String>> map and insert your inputs like below:
if(map.containsKey(words[1]))
{
List<String> list = map.get(words[1]);
list.add(words[0]);
map.put(words[1],list);
}
else
{
map.put(words[1],Arrays.asList(words[0]))
}
This way you will get list of names corresponding to each types(student/teacher) etc.
After that iterate over the map and print the list.
I think for a small amount of occupations it's reasonable to accomplish this using just array lists. I think the part you are having trouble with is the input structure so I'll help you out with an example of how to do that part and let you handle the filtering on your own:
private List<String> teachers = new ArrayList<>();
private List<String> students = new ArrayList<>();
private List<String> janitors = new ArrayList<>();
public void seperatePeople(){
Scanner in = new Scanner(System.in);
while(true){
//Keep getting the next line in an infinite loop
String line = in.nextLine();
if(line.equals("Done")){
break; //end the loop
}else{
//Split on the spaces
String[] personArray = line.split(" ");
//Remember each line is structured like : name, occupation
//So when we split the line the array list we get from it
//will be in the same order
putInArray(personArray[0], personArray[1]);
}
}
//Do whatever printing you have to do down here
}
private void putInArray(String name, String occupation) {
//filter and add to the correct list in here
}
If you wanted to implement this using a hashmap the input method would be the same, but instead of putting names into 3 pre-made occupation arraylists you create arraylists and put them inside a hashmap as you go:
private HashMap<String, List<String>> peopleHashMap = new HashMap<>();
public void seperatePeople(){
Scanner in = new Scanner(System.in);
while(true){
//Keep getting the next line in an infinite loop
String line = in.nextLine();
if(line.equals("Done")){
break; //end the loop
}else{
//Split on the spaces
String[] personArray = line.split(" ");
//Remember each line is structured like : name, occupation
//So when we split the line the array list we get from it
//will be in the same order
putInArray(personArray[0], personArray[1]);
}
}
//You can get all the keys that you created like this
List<String> keys = new ArrayList<>(peopleHashMap.keySet());
}
private void putInArray(String name, String occupation) {
if(peopleHashMap.containsKey(occupation)){
//If the key (occupation in this case) is already in the hashmap, that means that we previously
//made a list for that occupation, so we can just the name to that list
//We pull out a reference to the list
List<String> listOfNames = peopleHashMap.get(occupation);
//And then put the new name into that list
listOfNames.add(name);
}else{
//If the key isn't in the hashmap, then we need to make a new
//list for this occupation we haven't seen yet
List<String> listOfNames = new ArrayList<>();
//We then put the name into the new list we made
listOfNames.add(name);
//And then we put that new list with the into the hashmap with the occupation as the key
peopleHashMap.put(occupation, listOfNames);
}
}

Java Convert List<String> to List<Object>

I've two classess CsvRead and MyOwnClass.
In CsvRead I've a method public static List getDataFromCsv(); It returns list of all data. And this data I want to take in another method in class MyOwnClass and return there as list of objects of My OwnClass
It looks like this:
List<String> dataFromCsv = new ArrayList<String>();
And in another class, I want to convert it to List<Object> of my class.
private static List<String> getDataFromCsvClass = new ArrayList<String>();
getDataFromCsvClass = CsvReader.getAllCsvData(filename);
String name = dataFromCsv[0];
String surname = dataFromCsv[1];
String birth = dataFromCsv[2];
I want to return new MyOwnClass(name, surname, birth);
MY ERROR: array required but List found: String name = allData[0]; etc
You can create a method to convert a String to MyOwnClass and use stream to map the elements, e.g.:
public static MyOwnClass convertToObject(String element){
String[] tokens = element.split(",");
return new MyOwnClass(tokens[0], tokens[1], tokens[2]);
}
//code to convert
List<String> dataFromCsv = new ArrayList<String>();
List<MyOwnClass> list = dataFromCsv.stream()
.map(e -> convertToObject(e))
.collect(Collectors.toList());
However, this may not work if let's say name or surname contains comma. In which case, I would recommend having a look at OpenCSV library and this example of how to read csv into objects.
Supposing that the list contains the name, surname and birth in every group of 3 strings (i.e., the elements on index 0, 3, 6, 9 etc. contain the name), you might try the following:
public List<MyOwnClass> convertCsvData(List<String> csv_data)
{
// Initialize result
List<MyOwnClass> result;
result = new ArrayList<MyOwnClass>();
// Parse data
int counter;
String name;
String surname;
String birth;
for (counter = 0; counter < csv_data.size(); counter += 3)
{
name = csv_data.get(counter);
surname = csv_data.get(counter + 1);
birth = csv_data.get(counter + 2);
result.add(new MyOwnClass(name, surname, birth));
}
// Done
return (result);
} // convertCsvData
Somthing like this :
private static MyOwnClass toMyOwnClass(String str){
String[] object= str.split(",");
return new MyOwnClass(object[0], object[1], object[2]);
}
List<String> dataFromCsv = new ArrayList<String>();
List<MyOwnClass> list = new ArrayList<>();
for(String string : dataFromCsv ){
if(StringUtils.isNoneEmpty(string)){
list.add(toMyOwnClass(string));
}
}
And then you return your list

incompatible type of double array and properties string.split()

public static void main(String[] args)
{
String input="jack=susan,kathy,bryan;david=stephen,jack;murphy=bruce,simon,mary";
String[][] family = new String[50][50];
//assign family and children to data by ;
StringTokenizer p = new StringTokenizer (input,";");
int no_of_family = input.replaceAll("[^;]","").length();
no_of_family++;
System.out.println("family= "+no_of_family);
String[] data = new String[no_of_family];
int i=0;
while(p.hasMoreTokens())
{
data[i] = p.nextToken();
i++;
}
for (int j=0;j<no_of_family;j++)
{
family[j][0] = data[j].split("=")[0];
//assign child to data by commas
StringTokenizer v = new StringTokenizer (data[j],",");
int no_of_child = data[j].replaceAll("[^,]","").length();
no_of_child++;
System.out.println("data from input = "+data[j]);
for (int k=1;k<=no_of_child;k++)
{
family[j][k]= data[j].split("=")[1].split(",");
System.out.println(family[j][k]);
}
}
}
i have a list of family in input string and i seperate into a family and i wanna do it in double array family[i][j].
my goal is:
family[0][0]=1st father's name
family[0][1]=1st child name
family[0][2]=2nd child name and so on...
family[0][0]=jack
family[0][1]=susan
family[0][2]=kathy
family[0][3]=bryan
family[1][0]=david
family[1][1]=stephen
family[1][2]=jack
family[2][0]=murphy
family[2][1]=bruce
family[2][2]=simon
family[2][3]=mary
but i got the error as title: in compatible types
found:java.lang.String[]
required:java.lang.String
family[j][k]= data[j].split("=")[1].split(",");
what can i do?i need help
nyone know how to use StringTokenizer for this input?
Trying to understand why you can't just use split for your nested operation as well.
For example, something like this should work just fine
for (int j=0;j<no_of_family;j++)
{
String[] familySplit = data[j].split("=");
family[j][0] = familySplit[0];
String[] childrenSplit = familySplit[1].split(",");
for (int k=0;k<childrenSplit.length;k++)
{
family[j][k+1]= childrenSplit[k];
}
}
You are trying to assign an array of strings to a string. Maybe this will make it more clear?
String[] array = data.split("=")[1].split(",");
Now, if you want the first element of that array you can then do:
family[j][k] = array[0];
I always avoid to use arrays directly. They are hard to manipulate versus dynamic list. I implemented the solution using a Map of parent to a list of childrens Map<String, List<String>> (read Map<Parent, List<Children>>).
public static void main(String[] args) {
String input = "jack=susan,kathy,bryan;david=stephen,jack;murphy=bruce,simon,mary";
Map<String, List<String>> parents = new Hashtable<String, List<String>>();
for ( String family : input.split(";")) {
final String parent = family.split("=")[0];
final String allChildrens = family.split("=")[1];
List<String> childrens = new Vector<String>();
for (String children : allChildrens.split(",")) {
childrens.add(children);
}
parents.put(parent, childrens);
}
System.out.println(parents);
}
The output is this:
{jack=[susan, kathy, bryan], murphy=[bruce, simon, mary], david=[stephen, jack]}
With this method you can directory access to a parent using the map:
System.out.println(parents.get("jack"));
and this output:
[susan, kathy, bryan]

Categories

Resources