Java query an ArrayList of predefined object - arraylist

I have an ArrayList (inputList) that parse this data:
id,name,quantity
1,foo,10
2,bar,20
3,foo,10
4,bar,10
5,qwerty,1
Code:
...
List<FooRow> inputList = new ArrayList<FooRow>();
inputList = br.lines().map(mapToFooRow).collect(Collectors.toList());
...
public class FooRow{
private Integer id;
private String name;
private Integer value;
}
I want to create a collectors that return me a list with the count of value grouped by name:
name,value
foo,20
bar,30
qwerty,1
How can I create a class Collectors to do this in the lambda expression?
Thanks.

You can use Collectors.groupingBy and Collectors.summingInt:
Map<String, Integer> result =
inputList.stream()
.collect(Collectors.groupingBy(
FooRow::getName, Collectors.summingInt(FooRow::getValue)));

Related

Merging two arrays without any duplicates [VB.NET]

The question being asked is as follows:
Implement the UniqueNames method. When passed two arrays of names, it will return an array containing the names that appear in either or both arrays. The returned array should have no duplicates.
For example, calling MergeNames.UniqueNames({'Ava', 'Emma', 'Olivia'}, {'Olivia', 'Sophia', 'Emma'}) should return an array containing Ava, Emma, Olivia, and Sophia in any order.
Starting Code:
Module Module1
Public Class MergeNames
Public Shared Function UniqueNames(names1() As String, names2() As String) As String()
Throw New NotImplementedException()
End Function
End Class
Public Sub Main()
Dim names1() As String = {"Ava", "Emma", "Olivia"}
Dim names2() As String = {"Olivia", "Sophia", "Emma"}
Console.WriteLine(string.Join(", ", MergeNames.UniqueNames(names1, names2))) ' should print Ava, Emma, Olivia, Sophia
End Sub
End Module
LINQ would be the easiest way to go here:
Dim combinedUniqueNames = names1.Union(names2).Distinct().ToArray()
Union will combine two lists, Distinct will remove duplicates and ToArray creates a new array from the result. As is pretty much always the case with LINQ extension methods, they can all be called on any IEnumerable(Of T). Your String arrays implement IEnumerable(Of String).
EDIT:
As per Jimi's comment, we just need:
Dim combinedUniqueNames = names1.Union(names2).ToArray()
I guess I should have realised, given that 'union' is a set operation and does exclude duplicates in a mathematical context.
import java.util.ArrayList;
import java.util.List;
public class MergeNames {
public static String[] uniqueNames(String[] names1, String[] names2) {
List<String> list= new ArrayList<String>();
for (String name: names1) {
if(!list.contains(name)) {
list.add(name);
}
}
for (String name: names2) {
if(!list.contains(name)) {
list.add(name);
}
}
String[] a= list.toArray(new String[list.size()]);
return a;
}
public static void main(String[] args) {
String[] names1 = new String[] {"Ava", "Emma", "Emma","Olivia"};
String[] names2 = new String[] {"Olivia", "Sophia", "Emma"};
System.out.println(String.join(", ", MergeNames.uniqueNames(names1, names2))); // should print Ava, Emma, Olivia, Sophia
}
}

Converting a JSON String To an ArrayList of Objects with GSON

We have the following json string:
jsonUserDataRecs=[{"G_ID1":1,"G_ID2":2,"G_ID3":3,"NAME":"g1"},{"G_ID1":4,"G_ID2":5,"G_ID3":5,"NAME":"g2"}]
Would like to convert it into the following data type:
ArrayList<USER_DATA_REC> userDataRecs;
We tried the following, but did not get any results:
userDataRecs = gson.fromJson(jsonUserDataRecs, new TypeToken<ArrayList<USER_DATA_REC>>() {}.getType());
When we run : userDataRecs.get(0).getNAME(), we did not get any results.
Any help will be greatly appreciated.
Thank you.
First make a POJO class:
public class UserDataRecord {
public int G_ID1;
public int G_ID2;
public int G_ID3;
public String NAME;
public String getNAME() {
return NAME;
}
}
Next use gson to deserialize your json string like so:
UserDataRecord[] userDataRecords = gson.fromJson(jsonUserDataRecs, UserDataRecord[].class);
Now you have an array of the deserialized user data records. You can manually convert this to a list if you need to, or just iterate it using a normal for loop.

OrmLite Foreign Collection to List

I try to use foreign collections in ORMLite. However, I dont know how to convert it into list. I try to do something like this :
public class Car implements Serializable {
#DatabaseField(columnName = "carId" , generatedId = true, id=true)
private int id;
#DatabaseField(columnName = "carNumber")
private String mNumber;
#DatabaseField(columnName = "carName")
private String mName;
#ForeignCollectionField(eager = true,columnName = "carParts")
private Collection<Part> mParts;
ArrayList<Part> parts = new ArrayList<>(mParts);
public ArrayList<Part> getParts() {
return parts;
}
public void setParts(ArrayList<Part> parts) {
this.parts = parts;
}
but when I try to use it I get exception :
java.lang.NullPointerException: collection == null
at this line :
ArrayList<Part> parts = new ArrayList<>(mParts);
please, help.
The reason is simple - you have to wait until mParts will be initialized by ORMLite library, then you can create ArrayList from it.
public ArrayList<Part> getParts() {
return new ArrayList<>( mParts );
}

How to retrieve mongodb field value stored as array of string into a java ArrayList

Document structure is:
db.lookupdata.insert({ parent_key : "category" , key : "accessories" , value : ["belts","cases","gloves","hair","hats","scarves","sunglasses","ties","wallets","watches"]})
i want to store array filed values in java array list
i am finding the document like this:
FindIterable<Document> iterable1 = docCollectionLookup.find(Filters.eq("parent_key", "category"));
Iterator<Document> iter1=iterable1.iterator();
while(iter1.hasNext())
{
Document theObj = iter1.next();
categotyLookUpMap.put(theObj.getString("key"), list);
}
now here how can i retrieve array field values(key:"value") in ArrayList
You can retrieve array field values(key:"value") in ArrayList just like how you retrieve string field key. Please refer below:
FindIterable<Document> iterable1 = docCollectionLookup.find(Filters.eq("parent_key", "category"));
Iterator<Document> iter1=iterable1.iterator();
//Create a HashMap variable with type <String,ArrayList>,according to your needs
Map<String,ArrayList> categotyLookUpMap = new HashMap<String,ArrayList>();
while(iter1.hasNext())
{
Document theObj = iter1.next();
//Get method of Document class will return object,parse it to ArrayList
categotyLookUpMap.put(theObj.getString("key"), (ArrayList)theObj.get("value"));
}
Alternatively, you can use Morphia which is MongoDB object-document mapper in Java. You can setup dependency / download JAR from here
First, create LookupData class to map to lookupdata collection. Annotation #Id is required else will throw exception with message "No field is annotated with #Id; but it is required". So create an _id field for it.
#Entity("lookupdata")
public class LookupData {
#Id
String _id ;
#Property("parent_key")
String parentKey;
String key;
ArrayList<String> value;
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getParentKey() {
return parentKey;
}
public void setParentKey(String parentKey) {
this.parentKey = parentKey;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public void setValue(ArrayList<String> value) {
this.value = value;
}
public ArrayList<String> getValue() {
return value;
}
}
Retrieve array field values as below:
MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost"));
Morphia morphia = new Morphia();
morphia.map(LookupData.class);
//lookupdata collection is under my local db "tutorials" in this case
Datastore datastore = morphia.createDatastore(mongoClient, "tutorials");
Map<String,ArrayList> categotyLookUpMap = new HashMap<String,ArrayList>();
LookupData lookupData = datastore.find(LookupData.class).get();
categotyLookUpMap.put(lookupData.getKey(), lookupData.getValue());

Sorting an ArrayList by two different properties

So I have a HashMap<String, Integer> which represents the number of times a certain word has been encountered in a sentence. What I want to do is put all the words in an ArrayList<String>, sorted first by the number of times a word has been encountered, and then break ties by alphabetical order. How would I go about doing that? My code looks something like this:
public class MyClass {
private HashMap<String, Integer> map;
public ArrayList<String> Order() {
ArrayList<String> temp = new ArrayList<>();
(...)
}
You'll need to use a custom comparator. For the comparison method, you'll need to return a negative value if the first argument should be treated as less than the second, 0 if they are equal, and a positive value if the first argument should be treated as greater than the second.
Note that this sorts the ArrayList in descending order according to the integer value
import java.util.Comparator;
import java.util.HashMap;
public class CustomComparator implements Comparator<String>
{
HashMap<String, Integer> map;
public CustomComparator(HashMap<String, Integer> comparisonMap)
{
map = comparisonMap;
}
#Override
public int compare(String s1, String s2)
{
int count1 = map.get(s1);
int count2 = map.get(s2);
if (count1 == count2)
return s1.compareTo(s2);
return count2 - count1;
}
}
Two steps to create and sort the ArrayList:
First, add every key from the HashMap to the ArrayList
ArrayList<String> result = new ArrayList<String>(map.size());
result.addAll(map.keySet());
Then, sort the ArrayList using the custom comparator:
Collections.sort(result, new CustomComparator(map));