java - List remove specific object base on object property [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Supposed I have a list of objects
[
Post(postid=1, title=testtitle1, post=test, created_at=null, updated_at=null),
Post(postid=2, title=testtitle2, post=test, created_at=null, updated_at=null),
Post(postid=4, title=testtitle4, post=test, created_at=null, updated_at=null),
]
and I have an incoming request like this:
[
Post(postid=4, title=zzzzzzz, post=testpost, created_at=null, updated_at=null)
]
How can I replace the old post with post id 4
Post(postid=4, title=testtitle4, post=test, created_at=null, updated_at=null),
with the new request
[
Post(postid=4, title=zzzzzzz, post=testpost, created_at=null, updated_at=null)
]
so that the list will become like this
[
Post(postid=1, title=testtitle1, post=test, created_at=null, updated_at=null),
Post(postid=2, title=testtitle2, post=test, created_at=null, updated_at=null),
Post(postid=4, title=zzzzzzz, post=testpost, created_at=null, updated_at=null)
]

There are many ways, one of them is :
posts.removeIf(p -> Objects.equals(newPost().getId(), p.getId()));
posts.add(newPost);

I recommend you to use Map data structure for your usecase, instead of using list:
Write code like below:
public class PostBase {
private Map<Integer,Post> posts = new HashMap();
public void addPost(Post post) {
posts.put(post.getPostid(), post);
}
public Post getPost(int id){
return posts.get(id);
}
}
If you still want to use list, you can remove existing element by find element by id and add new one like below(similar to answered by YCF_L):
Post newpost = new Post(4, "xxx", "tt", null, null);
postlist.removeIf((post)->post.getPostid() == newpost.getPostid());
postlist.add(newpost);

Just do,
for(Post post : posts) {
if(idOfIncomingRequest.equals(post.postid)) {
// update your data here
}
}

Related

Posting raw json array using postman without POJO

I am trying to post a raw json array using retrofit but it adds an additional tag in front of the array in the body. The data I want to post is as below:
[
{
"id": "b354dd-ea44-8c3s6",
"values":"1",
"checksum": "A02",
},
{
"id": "t527sh-ea44-8c3s6",
"values":"0",
"checksum": "A32",
}
]
The problem that I am facing is, retrofit adds and extra tag "values" in front of this array:
{"values": [
{
"id": "b354dd-ea44-8c3s6",
"values":"1",
"checksum": "A02",
},
{
"id": "t527sh-ea44-8c3s6",
"values":"0",
"checksum": "A32",
}
]
}
Because of the extra "values" tag, the server is not accepting the data. Is there any way to prevent retrofit from putting in the tag? The array that I am passing to the retrofit request is JSONArray.
I cannot create a POJO because I would have to send the data as it is, without any manipulation.
Any help would be appreciated.

Group JSON based on ID [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
i have a json
{
"content": [
{
"idnumber": "666",
"name": "mark",
"type": "band",
"tools": [
{
"idtools": "5657",
"blabla": null,
"blabla": false,
}
]
},
{
"idnumber": "666",
"name": "mark",
"type": "band",
"tools": [
{
"idtools": "5658",
"blabla": null,
"blabla": false
}
]
}
]
}
inside content array, i have 2 json. i want to change my json into this, because they have same id number.
{
"content": [
{
"idnumber": "666",
"name": "mark",
"type": "band",
"tools": [
{
"idtools": "5657",
"blabla": null,
"blabla": false,
},
{
"idtools": "5658",
"blabla": null,
"blabla": false
}
]
}
]
}
how to do that using distinct or filter?
i tried to distinct it and map it but still have error.
Assuming the following objects that match your JSON structure (for sake of brevity, I use Lombok):
#Data
#AllArgsConstructor
#NoArgsConstructor
class Content {
int idNumber;
String name;
String type;
List<Tool> tools;
}
#Data
#AllArgsConstructor
#NoArgsConstructor
class Tool {
int idTools;
String blabla;
}
You can use the Stream API with groupingBy by the id and reduce the values into a single one.
List<Content> mergedContents = contents.stream()
.collect(Collectors.groupingBy(Content::getIdNumber))
.values()
.stream()
.reduce(
new ArrayList<>(), // mutable List
(left, right) -> {
Content content = right.get(0); // they are same (by id)
List<Tool> tools = right.stream() // from each new list
.flatMap(c -> c.getTools().stream()) // .. flatmap the tools
.collect(Collectors.toList()); // .. and extract to a list
content.setTools(tools); // set the List<Tool>
left.add(content); // add the Content
return left; // return the left list
},
(left, right) -> left); // only for parallel Stream
The resulting structure comming from Collectors.groupingBy(Content::getIdNumber) is Map<Integer, List<Content>>. The subsequent mutable reduction on the map values (Collection<List<Content>>) merges each List<Content> with identical Content.id into a single Content with flatmapped List<Tools>. The List with a these modified Content is returned as a result of the reduction.
Sample data
List<Content> contents = new ArrayList<>();
contents.add(new Content(666, "Mark", "Band",
Collections.singletonList(new Tool(5657, null))));
contents.add(new Content(666, "Mark", "Band",
Collections.singletonList(new Tool(5658, null))));
List<Content> mergedContents = /* solution */
mergedContents.forEach(System.out::println);
Main.Content(idNumber=666, name=Mark, type=Band, tools=[Main.Tool(idTools=5657, blabla=null), Main.Tool(idTools=5658, blabla=null)])
This is equal to what your JSON samples.

Access sub environment variable in Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have the following environment variable:
$ printenv
...
VCAP_SERVICES={"mariadbent":[{
"label": "mariadbent",
"provider": null,
"plan": "usage",
"name": "stackoverflow-database",
"tags": [
"mariadb",
"mysql"
],
"instance_name": "stackoverflow-database",
"binding_name": null,
"credentials": {
"host": "some-url-to-the-database.service",
"hostname": "some-url-to-the-database.service",
"port": 7689,
"name": "JDFJHDJF_DFJKDHFUD_DFUZDKFJDKJF",
"database": "JDFJHDJF_DFJKDHFUD_DFUZDKFJDKJF",
"username": "hsdfhsjkfhsjkhfjk",
"password": "iuzwerhsdjkfjkasd",
"database_uri": "mysql://dfdfdfdfdf:jrb4j4QxzgbAcfLk#some-url-to-the-database.service:3306/JDFJHDJF_DFJKDHFUD_DFUZDKFJDKJF?reconnect=true",
"uri": "mysql://dfdfdfdfdf:jrb4j4QxzgbAcfLk#some-url-to-the-database.service:3306/JDFJHDJF_DFJKDHFUD_DFUZDKFJDKJF?reconnect=true",
"jdbcUrl": "jdbc:mysql://some-url-to-the-database.service:3306/JDFJHDJF_DFJKDHFUD_DFUZDKFJDKJF?user=dfdfdfdfdf&password=jrb4j4QxzgbAcfLk"
},
"syslog_drain_url": null,
"volume_mounts": [
]
}]}
I can get the whole "pack" of data with System.out.println("VCAP_SERVICES: " + System.getenv("VCAP_SERVICES"));, but I would like to extract some field in the above output, like the username.
How could I do that?
Your VCAP_SERVICE hold an json. You can use an json parser to get a value from it.
Here is an example using Jackson, but there a more libs which can do this.
try{
String json = System.getenv("VCAP_SERVICES"); //NullPointerException, SecurityException
JsonNode jsonNode = (new ObjectMapper()).readTree(json); //IOException
if(jsonNode.has("mariadbent") && jsonNode.get("mariadbent").isArray()){
for(JsonNode elem : jsonNode.get("mariadbent")){
if(elem.has("credentials")){
JsonNode cred = elem.get("credentials");
if(cred.has("host")){
System.out.println(
cred.get("host").asText() //some-url-to-the-database.service
);
}else{ System.out.println("no host"); }
}else{ System.out.println("no credentials"); }
}
}else{ System.out.println("no mariadbent or not array"); }
}catch(Exception e){ e.printStackTrace(); }
For this you need lib Jackson Databind: https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind/2.9.9.3

Elasticsearch Java API query [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I`m newbie with elasticsearch querybuilder, Could someone give a constructed query for this below one in Java API
curl -XGET "http://localhost:9200/mone/mone/_search?pretty=true" -d'
{
"query": {
"filtered": {
"query": {
"query_string": {
"query": "ABC",
"fields": ["Data.Type"]
}
},
"filter": {
"term": { "Data.Date": "01.06.2014" }
}
}
}
}'
Using FilterQueryBuilder I got it to work
FilteredQueryBuilder builder = QueryBuilders.filteredQuery(QueryBuilders.queryString("Spectra"), FilterBuilders.termFilter("Data.Date", "01.06.2014"));
SearchResponse response = elasticClient.prepareSearch("mone")
.setTypes("mone")
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setQuery(builder)
.execute()
.actionGet();
System.out.println(response);
Hope this answer will be useful to some newbies like me.

creating JSON format output [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am trying to write a program which can create an output in JSON format, how would be best way of doing this? and programming languages?
This is an example output of JSON (expected output) which I need to input in the Name, Gender, Qualification and other attributes in a user friendly way during the execution of script. And in which outputs in following JSON format. Sorry, I am new in programming, but so much interested to learn Perl (or) Python (or) Java. What could be the best here?
Any suggestions?
P.S Sorry I am quite new to JSON as well, please apologize me for this basic one.
[
{
"Name":"Steven Mark",
"gender":"male",
"Qualification": {
"college":"Bachelor in Science",
"tech":"certified pro"
},
"contributions": [
{
"name":"biography",
"type":"book",
},
]
},
{
"Name":"Andrea Mark",
"Gender":"female",
"Qualifications": {
"college":"Bachelor in physics",
},
"contributions": [
{
"name":"my insights",
"type":"movie",
},
]
}
]
Virtually every language has a JSON library, including Perl.
use JSON;
my $data = [
{
"Name" => "Steven Mark",
"gender" => "male",
"Qualification" => {
"college" => "Bachelor in Science",
"tech" => "certified pro"
},
"contributions" => [
{
"name" => "biography",
"type" => "book",
},
]
},
{
"Name" => "Andrea Mark",
"Gender" => "female",
"Qualifications" => {
"college" => "Bachelor in physics",
},
"contributions" => [
{
"name" => "my insights",
"type" => "movie",
},
]
}
];
print(encode_json($data));
If you agree to use ANY programming language, i can suggest python. With its json lib you can do following (lines with # is comments):
# import lib
import json
# fill data into variable (this is list with dict objects inside):
data = [{"name":"john"},{"name": "bill"}]
# dump json
json.dumps(data)
Which will output your data as json.
You can start writing python using something from https://wiki.python.org/moin/BeginnersGuide
If you are going to use Python, you can try to use simplejson or json module to create a json object.
For example,
try:
import simplejson
except:
import json
data = dict(a=1,b=2)
with open("results.json", "w") as fp:
json.dump(data, fp, indent=3, encoding="utf-8")
For dumping, json is faster than simplejson (but not by an order of magnitude). For loading, simplejson is faster (but not by an order of magnitude).
You can check here for more detailed comparison between simplejson and json.

Categories