How do I check if any arraylist contains specific string - java

I am trying with below code :
public void verifyCategorySlugsInSearchcall(BaseDTO baseDTO, String jsonResponse) {
List<String> categoryList = JsonPath.read(jsonResponse,
"response.groups.DEFAULT_GROUP.documents[*].categorySlugs[*]");
CustomReporter.reportInfoWithOutLineBreak("Category from search call Response:" + categoryList);
Assert.assertTrue(categoryList.size() > 0, "No category slug name was displayed.");
CustomReporter.reportInfoWithOutLineBreak("Category Slug from search call Response:" + categoryList);
Assert.assertTrue(categoryList.contains(baseDTO.getPsCallDetails().getCategory()),
"Category Name was not matching. Actual:" + categoryList + ".Expected:"
+ baseDTO.getPsCallDetails().getCategory());
}
My arrayalist contains all category name :
eg: ["apple-tv-apple-tv-4k","apple-tv-apple-tv-4k","apple-tv-apple-tv"]
Need to search apple-tv contains in this array. My code is giving error as not contains apple-tv in particular category.

Using streams:
boolean result = categoryList.stream()
.anyMatch(c -> c.contains("apple-tv"));
If you instead want to generate a new list containing only categories having apple-tv somewhere in the name, then use filter:
List<String> output = categoryList.stream()
.filter(c -> c.contains("apple-tv"))
.collect(Collectors.toList());

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
}

Adding element to List from csv file like Arraylist.add

Here is my code:
public static Map<String, List<Customer>> readCustomerData() throws IOException {
Map<String, List<Customer>> customers =
Files.lines(Paths.get("customer.csv"))
.map(line -> line.split("\\s*,\\s*"))
.map(field -> new Customer(
Integer.parseInt(field[0]), field[1],
Integer.parseInt(field[2]), field[3]))
.collect(Collectors
.groupingBy(Customer::getName));
System.out.println (customers);
return customers;
}
I notice that this code read my data in the csv file into one element like this:
(Ali = ["1 Ali 1201345673 Normal"] , Siti = ["2 Siti 1307891435 Normal"])
But in my thinking , I would like to read the data like the array list such as for Ali: 1 is an element , Ali is an element , 1201345673 is an element and Normal is another element in the list in the Map customer. How can I modify my code to do such a thing?
This is my Customer class just in case:
public class Customer {
private int customerNo;
private String name;
private int phoneNo;
private String status;
public Customer () {}
public Customer (int customerNo, String name, int phoneNo, String status){
this.customerNo = customerNo;
this.name = name;
this.phoneNo = phoneNo;
this.status = status;
}
public String getName(){
return name;
}
public String toString(){
return customerNo + " " + name + " " + phoneNo + " " + status;
}
Here is my csv file:
1,Ali,1201345673,Normal
2,Siti,1307891435,Normal
Thank you for your attention.
Assuming that the customer names are unique, there's no need to return a Map<String, List<Customer>>, since each List will contain a single Customer.
You can change your code to:
Map<String, Customer> customers =
Files.lines(Paths.get("customer.csv"))
.map(line -> line.split("\\s*,\\s*"))
.map(field -> new Customer(
Integer.parseInt(field[0]), field[1],
Integer.parseInt(field[2]), field[3]))
.collect(Collectors.toMap(Customer::getName, Function.identity()));
And if the names are not unique, you can index the customers by the customer IDs.
As for I would like to read the data like the array list such as for Ali: 1 is an element , Ali is an element , 1201345673 is an element and Normal is another element in the list in the Map customer - this doesn't make sense to me. You already create a Customer object from each line of your input, which is much more useful and type safe compared to a List of properties.

Criteria inside JsonPath

I'm trying to filter jsonPath by type. To extract Integers
I would expect this will return nothing as 'xx' is not integer:
JsonPath.read("{'status': 'xx'}", "$.status", Criteria.where(".status").is(Integer.class));
Similarly this
JsonPath.read("{'status': 'xx'}", "$.status", Criteria.where(".status").eq(200));
both cases returns String = "xx"
I would expect it to return either null or empty string as it doesn't match number 200.
Correct #i.bondarenko, I would simply add - for the first check of searching whether status value is an Integer - that he/she should use a Pattern to pass to the filter, like for example
Pattern numberPattern = Pattern.compile("\\d+");
Filter filter = filter(where("status").regex(numberPattern));
Object test = JsonPath.read("{\"status\": \"xx\"}", "$[?].status", filter);
System.out.println("Test : " + test);
That will print Test : []
UPDATED
It is a JSONArray indeed, therefore, you already have the Integers of your whole JSON in that array (if they exist). For example,
Pattern numberPattern = Pattern.compile("\\d+");
Filter filter = filter(where("status").regex(numberPattern));
net.minidev.json.JSONArray test = JsonPath.read("{\"status\": 300}", "$[?].status", filter);
if (!test.isEmpty()) {
for (Object object : test) {
System.out.println("Test : " + object.toString());
}
}
So, there is no need to add try-catch, it is enough to just check the size of your JSONArray result
You should use $[?].status as json path for criteria.
Also where("field").is("value") accept value but not a class.
You could have a look at implementation of Criteria.eq(...)
public Criteria eq(Object o) {
return is(o);
}
Here is the code:
public static void main(String[] args) {
Criteria criteria = Criteria.where("status").gt(10);
Object read = JsonPath.read("{'status': 18}", "$[?].status", criteria);
System.out.println("First: " + read);
read = JsonPath.read("{'status': 2}", "$[?].status", criteria);
System.out.println("Second: " + read);
criteria = Criteria.where("status").is("value");
read = JsonPath.read("{'status': 'value'}", "$[?].status", criteria);
System.out.println("Third: " + read);
criteria = Criteria.where("status").is("value");
read = JsonPath.read("{'status': 'NON'}", "$[?].status", criteria);
System.out.println("Third: " + read);
}
Output:
First: [18]
Second: []
Third: ["value"]
Third: []

get specify word from string php codeigniter

I have an input for search ,
i search for "res"
<input type="text" name="search"I/>
i use Like method to get search results,
$txt = $this -> input -> post("search");
$this -> db -> like('title', $txt);
if ($sql = $this -> db -> get('ads') -> result()) {
$data['posts'] = $sql;
print_r($sql);
}
and get this results :
some text restaurant and other
some text result
my resume
i want to show the liked word
extract the word from strings and remove other texts
i want this :
restaurant
result
resume
You can split the found string into an array (explode) and then search this array with the given string (preg_grep) and output the found strings.
<?php
$searchString = "/res/";
$foundString = "some text restaurant and other";
$explode = explode(" ", $foundString);
$searched = preg_grep($searchString, $explode);
foreach($searched as $item) {
echo $item . " ";
}

Ldap get users in a distribution list

I'm trying to get all the users of a DL using below code.The code is working as expected. However, I'm not able to get AD usernames for some users. Ex. First row of the o/p has username rkama but not the second row. Is this LDAP data issue or is there a different way to get user name/email address in a DL.
O/p
Entry is : CN=Ay\,Ram(rkama),OU=Site-SJN,OU=Accounts_User,DC=corp,DC=XXX,DC=com
Entry is : CN=Wang\,Peter(),OU=Site-SJN,OU=Accounts_User,DC=corp,DC=XXX,DC=com
public ArrayList<String> getAllDLs(String dlname) throws NamingException {
ArrayList<String> dls = new ArrayList<String>();
String attributes[] = { "member", "displayName" };
createDLContext();
SearchControls ctrl = new SearchControls();
ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
ctrl.setReturningAttributes(attributes);
String search = "(&(objectClass=group)((sAMAccountName="+dlname+"*)))";
NamingEnumeration enumeration = dlContext.search("", search, ctrl);
while (enumeration.hasMoreElements()) {
SearchResult result = (SearchResult) enumeration.next();
System.out.println("Found match & result is : " + result);
NamingEnumeration<?> n2 = result.getAttributes().get("member").getAll();
while (n2 != null && n2.hasMore()) {
String dlList = (String) n2.next();
System.out.println("Entry is : " + dlList);
}
}
dlContext.close();
return dls;
}
I think you need to escape the \ character. Have a look at http://www.rlmueller.net/CharactersEscaped.htm
The member element only contains a DN for the user, this is not the username or password of the account, but a value that can be put back into the search to get the user information (including cn - the name of the user, and sAMAccountName - the userid of the user).
So you need to feed the dlList value into a second search (cleanly) e.g.
NamingEnumeration searchResult = dlContext.search("", "(dn={1})", new Object[]{ dlList }, ctrl);
Trying to construct the search with a simple string like "(&(objectClass=group)((sAMAccountName="+dlname+"*)))" will yield problems because the elements of the returned string will need to be escaped before putting it into the search (the \ for example).

Categories

Resources