Here are 4 inputs along with their results:
Option 1:
{country=United States, city=Los Angeles, name=Johnson, age=33}
name = 'Johnson' and country = 'United States' and city = 'Los Angeles' and age = '33'
Option 2:
{country=United States, city=Los Angeles, name=null, age=33}
country = 'United States' and city = 'Los Angeles' and age = '33'
Option 3:
{country=United States, city=null, name=null, age=33}
country = 'United States' and age = '33'
Option 4:
{country=United States, city=null, name=null, age=null}
country = 'United States'
package com.codegym.task.task22.task2208;
import java.util.HashMap;
import java.util.Map;
/*
Build a WHERE query
*/
public class Solution {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("name", null); // "Johnson"
map.put("country", "United States"); // "United States"
map.put("city", null); // "Los Angeles"
map.put("age", "33"); // "33"
System.out.println(getQuery(map));
}
public static String getQuery(Map<String, String> params) {
if (params.size() % 4 != 0)
return null;
StringBuilder sb = new StringBuilder();
if (params.get("name") != null)
sb.append("name = '").append(params.get("name")).append("'");
if (params.get("country") != null) {
if (params.get("name") == null)
sb.append("country = '").append(params.get("country")).append("'");
else
sb.append(" and country = '").append(params.get("country")).append("'");
}
if (params.get("city") != null) {
if (params.get("name") == null && params.get("country") == null)
sb.append("city = '").append(params.get("city")).append("'");
else
sb.append(" and city = '").append(params.get("city")).append("'");
}
if (params.get("age") != null) {
if (params.get("names") == null && params.get("country") == null && params.get("city") == null)
sb.append("age = '").append(params.get("age")).append("'");
else
sb.append(" and age = '").append(params.get("age")).append("'");
}
return sb.toString();
}
}
/*
Build a WHERE query - Создайте запрос WHERE
Build part of a WHERE query using StringBuilder.
If a parameter is null, then it shouldn't be included in the query.
**Создайте часть запроса WHERE с помощью StringBuilder.
Если параметр имеет значение null, его не следует включать в запрос.
Example:
{name=Johnson, country=United States, city=Los Angeles, age=null}
Result:
name = 'Johnson' and country = 'United States' and city = 'Los Angeles'
Requirements:
1. The getQuery method must have one Map parameter.
2. The getQuery method must return a String.
3. The getQuery method must be static.
4. The getQuery method must return a string built according to the rules specified in the task conditions.
*/