I have a List<UserVO>
Each UserVO has a getCountry()
I want to group the List<UserVO> based on its getCountry()
I can do it via streams but I have to do it in Java6
This is in Java8. I want this in Java6
Map<String, List<UserVO>> studentsByCountry
= resultList.stream().collect(Collectors.groupingBy(UserVO::getCountry));
for (Map.Entry<String, List<UserVO>> entry: studentsByCountry.entrySet())
System.out.println("Student with country = " + entry.getKey() + " value are " + entry.getValue());
I want output like a Map<String, List<UserVO>>:
CountryA - UserA, UserB, UserC
CountryB - UserM, User
CountryC - UserX, UserY
Edit: Can I further reschuffle this Map so that I display according to the displayOrder of the countries. Display order is countryC=1, countryB=2 & countryA=3
For example I want to display
CountryC - UserX, UserY
CountryB - UserM, User
CountryA - UserA, UserB, UserC
This is how you do it with plain Java. Please note that Java 6 doesn't support the diamond operator so you have use <String, List<UserVO>> explicitly all the time.
Map<String, List<UserVO>> studentsByCountry = new HashMap<String, List<UserVO>>();
for (UserVO student: resultList) {
String country = student.getCountry();
List<UserVO> studentsOfCountry = studentsByCountry.get(country);
if (studentsOfCountry == null) {
studentsOfCountry = new ArrayList<UserVO>();
studentsByCountry.put(country, studentsOfCountry);
}
studentsOfCountry.add(student);
}
It's shorter with streams, right? So try to upgrade to Java 8!
To have a specific order based on the reversed alphabetical String, as mentioned in the comments, you can replace the first line with the following:
Map<String,List<UserVO>> studentsByCountry = new TreeMap<String,List<UserVO>>(Collections.reverseOrder());
Related
Tell me please
How can i get active directory domain name from java
I tried this
System.out.println(System.getenv("USERDOMAIN"));
but I only get the name of the computer
======================
I did so
InetAddress inet = InetAddress.getLocalHost();
InetAddress[] ips = InetAddress.getAllByName(inet.getCanonicalHostName());
usernameId.setText(System.getProperty("user.name"));
if (ips != null) {
for (int i = 0; i < ips.length; i++) {
String[] str = ips[i].toString().split("/");
if (!(str[1].startsWith("169") || str[1].contains(":")))
System.out.println("Computer name: " + str[0] + "\nIp address: " + str[1]);
computernameId.setText(str[0]);
And i get ip address and computername.domainname
Try using
System.out.println(System.getenv("USERDNSDOMAIN"));
If that does not work, you can (as James Tanner said) try parsing through your system variables to find the one you want:
Map<String, String> envMap = System.getenv();
Iterator iter = envMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, String> pair = (Map.Entry<String, String>)iter.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
}
From this article, try checking the DomainName environment variable.
Or, from this question, try the LOGONSERVERvariable.
If that doesn't work, I'd recommend taking a look at your environment variables directly (directions vary depending on which version of Windows you're running) to find the one that actually contains the information you're looking for, then use that one.
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 7 years ago.
Improve this question
I have the following complex data-structure:
Map<String, Map<String,String>> URL_and_entities = new HashMap<String, Map<String,String>>();
on the inside of a loop I finally want to populate it but I can't figure out how.
This is my code, it's essentially a series of nested loops that make an HTTP request to determine if they share a relationship, which is revealed by the presence (or absence) of a url. I'm trying to save the URL (if it exists), and the two entities that evoked it:
for (String entity_1 : Q_value_references_for_sentence_entities)
{
for (String entity_2 : Q_value_references_for_sentence_entities)
{
String URL_czech = "http://milenio.dcc.uchile.cl/sparql?default-graph-uri=&query=PREFIX+%3A+%3Chttp%3A%2F%2Fwww.wikidata.org%2Fentity%2F%3E%0D%0ASELECT+*+WHERE+%7B%0D%0A+++%3A"
+ entity_1 + "+%3FsimpleProperty+%3A"
+ entity_2 + "%0D%0A%7D%0D%0A&format=text%2Fhtml&timeout=0&debug=on";
URL wikidata_page = new URL(URL_czech);
HttpURLConnection wiki_connection = (HttpURLConnection)wikidata_page.openConnection();
InputStream wikiInputStream = null;
try
{
// try to connect and use the input stream
wiki_connection.connect();
wikiInputStream = wiki_connection.getInputStream();
}
catch(IOException error)
{
// failed, try using the error stream
wikiInputStream = wiki_connection.getErrorStream();
}
// parse the input stream using Jsoup
Document docx = Jsoup.parse(wikiInputStream, null, wikidata_page.getProtocol()+"://"+wikidata_page.getHost()+"/");
Elements link_text = docx.select("table.sparql > tbody > tr:nth-child(2) > td > a");
//link_text.text();
for (Element l : link_text)
{
String output = l.text();
output = output.substring(0, output.length()-1);
list_of_relation_URLs.add( output );
URL_and_entities.put( output , (entity_1, entity_2));
}
}
}
I'm not oppoed to using that crazy google library of wonky data-strucs, I've used it before, but in this case I can't see a compelling reason why it would be any better than Map<String, Map<String,String>>
Update
I'm having trouble getting the values out. This doesn't work it seems
String first__english_lang_Q = retrieved_entities.getKey();
String second_english_lang_Q = retrieved_entities.getValue();
System.out.println("`(" + value + ")'" + "`( " + entity_1 + ", " + entity_2 + ")'");
You just need a tuple, You can use the apache common Pair
Map<String, Pair<String,String>> URL_and_entities = new HashMap<String, Pair<String,String>>();
URL_and_entities.put("something", Pair.of("left", "right"))
URL_and_entities.get("something").getLeft();
URL_and_entities.get("something").getRight();
Try this:
Map<String,String> entities;
for (String entity_1 : Q_value_references_for_sentence_entities)
{
for (String entity_2 : Q_value_references_for_sentence_entities)
{
entities = new HashMap<String, String>();
entities.put(entity_1, entity_2);
...check that URL exist and doesn't return null, and then convert it to a String...
URL_and_entities.put(output, entities);
}
}
}
I don't understand though, why you are using a Map to store the two entities. Unless you plan on using one entity to reference the second entity, you can simply store the two entities in a simple array (or technically even an ArrayList or HashSet would be better than a Map).
Just do:
Map<String, String[]> URL_and_entities = new HashMap<String, String[]>();
String [] entities = new String[2];
for (String entity_1 : Q_value_references_for_sentence_entities)
{
for (String entity_2 : Q_value_references_for_sentence_entities)
{
entities[0] = entity_1;
entities[1] = entity_2;
...check that URL exist and doesn't return null, and then convert it to a String...
URL_and_entities.put(output, entities);
}
}
}
Then to retrieve and print all the values in the set you just do:
for (String url: byLetter.keySet()) {
String [] retrievedValues = URL_and_entities.get(url);
System.out.println(url + " " + retrievedValues[0] + ", " + retrievedValues[1];
}
If using an ArrayList do:
for (String url: byLetter.keySet()) {
ArrayList retrievedValues = URL_and_entities.get(url);
System.out.println(url + " " + retrievedValues.get(0) + ", " + retrievedValues.get(1);
}
I have List<HashMap> of mail addressess, along with users ids (each entry in list looks like: id: 123, mail: "john#doe.com").
I want to make a HashMap in which every key is a domain name of e-mail address, and value is list of e-mails from that domain:
"foo.com":
[1]
id: 123,
mail: a#foo.com
[2]
id: 345
mail: b#foo.com
"bar.com":
[1]
id: 787,
mail: a#bar.com
[2]
id: 456
mail: b#bar.com
To achieve that, I do what's below. Problem is, when I try to add new list entry to list existing on domain entry, java adds new record to sortedAddresses instead of using present one. My prediction is containsKey() method always returns false.
HashMap<String, List> sortedAddresses = new HashMap<String, List>();
for(HashMap<String, String> r : this.lightUsersList){
String mail = r.get("email");
Integer uid = Integer.parseInt(r.get("id"));
try{
String[] mailSplit = mail.split("#");
String domain = mailSplit[1];
//if domain key doesn't exist, add it to hashmap
if(!sortedAddresses.containsKey(domain)){
List<HashMap> domainAddr = new ArrayList<HashMap>();
sortedAddresses.put(domain, domainAddr);
}
List<HashMap> domainAddr = sortedAddresses.get(domain);
sortedAddresses.remove(domain);
domainAddr.add(r);
sortedAddresses.put(domain, domainAddr);
}
catch(Exception e){
//to be implemented
System.out.println("Nie udalo sie dodac adresu " + mail + " do tablicy domenowej (" + e.getMessage() + ")");
}
//displaying hashmap summary (source from another SO thread)
Iterator it = sortedAddresses.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey() + " = " + sortedAddresses.get(pairs.getKey()).size());
it.remove(); // avoids a ConcurrentModificationException
}
}
Output I get:
foo = 1
bar = 1
foo = 1
bar = 1
Should be:
foo = 2
bar = 2
Okay, it seems that I see where I made a mistake. Of course Iterator part should be after for loop. My bad. Hate mondays.
I use this following code to extract all of the Keys start with "NAME:" and it return only over 5,000 records (There is over 60,000 keys in my index). Can anyone explain why it is happening or how can I extract all of the keys from Redis Database.
jedis.select(3);
Set<String> names=jedis.keys("NAME:*");
Iterator<String> it = names.iterator();
while (it.hasNext()) {
String s = it.next();
System.out.println(s);
}
When Redis server store many record, using jedis.keys() command can make it over-processing. Thus, result in it stop when the task is un-done.
Instead of it, you use jedis.hscan() so as to avoid above problem.
ScanParams scanParam = new ScanParams();
String cursor = "0";
int i = 0;
scanParam.match(prefix + "*");
scanParam.count(50000); // 2000 or 30000 depend on your
do {
ScanResult<Map.Entry<String, String>> hscan = jedis.hscan(key, cursor, scanParam);
// any code here
//
//
// check cursor
cursor = hscan.getStringCursor();
} while("0".equals(cursor));
It work well in your case.
You should not use the keys method for normal Redis usage as stated in the JavaDoc below.
http://javadox.com/redis.clients/jedis/2.2.0/redis/clients/jedis/Jedis.html#keys(java.lang.String)
Instead consider using Redis sets like this.
final Jedis jedis = new Jedis("localhost");
jedis.sadd("setName", "someValue");
jedis.smembers("setName");
jedis.close();
Try without NAME in keys search pattern.
Set<String> names = jedis.keys("*");
java.util.Iterator<String> it = names.iterator();
while(it.hasNext()) {
String s = it.next();
System.out.println(s + " : " + jedis.get(s));
}
I've decided to use ini file to store simple key-value pair configuration for my Java application.
I googled and searched stackoverflow and found that ini4j is highly recommended for parsing and interpreting ini files in Java. I spent some time reading the tutorial on ini4j site; however, I was not sure how to get all the key values for a setting in an ini file.
For instance, if I have a ini file like this:
[ food ]
name=steak
type=american
price=20.00
[ school ]
dept=cse
year=2
major=computer_science
and assume that I do not know names of keys ahead of time. How do I get the list of keys so that I can eventually retrieve the values according to keys? For instance, I would get an array or some kind of data structure that contains 'name', 'type', and 'price' if I get a list of keys for food.
Can someone show me an example where you would open an ini file, parse or interpret it so that an app knows all the structure and values of the ini file, and get the list of keys and values?
No guarantees on this one. Made it up in 5min.
But it reads the ini you provided without further knowledge of the ini itself (beside the knowledge that it consists of a number of sections each with a number of options.
Guess you will have to figure out the rest yourself.
import org.ini4j.Ini;
import org.ini4j.Profile.Section;
import java.io.FileReader;
public class Test {
public static void main(String[] args) throws Exception {
Ini ini = new Ini(new FileReader("test.ini"));
System.out.println("Number of sections: "+ini.size()+"\n");
for (String sectionName: ini.keySet()) {
System.out.println("["+sectionName+"]");
Section section = ini.get(sectionName);
for (String optionKey: section.keySet()) {
System.out.println("\t"+optionKey+"="+section.get(optionKey));
}
}
}
}
Check out ini4j Samples and ini4j Tutorials too. As often a not very well documented library.
I couldn't find anything in the tutorials so I stepped through the source, until I found the entrySet method. With that you can do this:
Wini ini = new Wini(new File(...));
Set<Entry<String, Section>> sections = ini.entrySet(); /* !!! */
for (Entry<String, Section> e : sections) {
Section section = e.getValue();
System.out.println("[" + section.getName() + "]");
Set<Entry<String, String>> values = section.entrySet(); /* !!! */
for (Entry<String, String> e2 : values) {
System.out.println(e2.getKey() + " = " + e2.getValue());
}
}
This code essentially re-prints the .ini file to the console. Your sample file would produce this output: (the order may vary)
[food]
name = steak
type = american
price = 20.00
[school]
dept = cse
year = 2
major = computer_science
The methods of interest are get() and keySet()
Wini myIni = new Wini (new File ("test.ini"));
// list section names
for (String sName : myIni.keySet()) {
System.out.println(sName);
}
// check for a section, section name is case sensitive
boolean haveFoodParameters = myIni.keySet().contains("food");
// list name value pairs within a specific section
for (String name : myIni.get("food").keySet() {
System.out.println (name + " = " + myIni.get("food", name)
}
In Kotlin:
val ini = Wini(File(iniPath))
Timber.e("Read value:${ini}")
println("Number of sections: "+ini.size+"\n");
for (sectionName in ini.keys) {
println("[$sectionName]")
val section: Profile.Section? = ini[sectionName]
if (section != null) {
for (optionKey in section.keys) {
println("\t" + optionKey + "=" + section[optionKey])
}
}
}