Convert Resultset into MapHow do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesHow can I initialise a static Map?How to convert List<Integer> to int[] in Java?How to convert a Map to List in Java?Easiest way to convert a List to a Set in JavaChecking for a null int value from a Java ResultSetHow to convert an Array to a Set in JavaConverting 'ArrayList<String> to 'String[]' in JavaHow to convert comma-separated String to ArrayList?

Why would future John risk sending back a T-800 to save his younger self?

Were Alexander the Great and Hephaestion lovers?

How to retract an idea already pitched to an employer?

Investing in a Roth IRA with a Personal Loan?

How do governments keep track of their issued currency?

What could have caused a rear derailleur to end up in the back wheel suddenly?

If you had a giant cutting disc 60 miles diameter and rotated it 1000 rps, would the edge be traveling faster than light?

What does the term "railed" mean in signal processing?

What makes an item an artifact?

PhD - Well known professor or well known school?

Inconsistent behavior of compiler optimization of unused string

Passing multiple files through stdin (over ssh)

Dual boot macOS Catalina 10.15 and macOS Mojave 10.14

Compiling c files on ubuntu and using the executable on Windows

How to build suspense or so to establish and justify xenophobia of characters in the eyes of the reader?

Using a found spellbook as a Sorcerer-Wizard multiclass

My coworkers think I had a long honeymoon. Actually I was diagnosed with cancer. How do I talk about it?

How is water heavier than petrol, even though its molecular weight is less than petrol?

How to tell your grandparent to not come to fetch you with their car?

What is the actual quality of machine translations?

Movie about a boy who was born old and grew young

Can a black dragonborn's acid breath weapon destroy objects?

Is open-sourcing the code of a webapp not recommended?

Smooth switching between 12 V batteries, with a toggle switch



Convert Resultset into Map


How do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesHow can I initialise a static Map?How to convert List<Integer> to int[] in Java?How to convert a Map to List in Java?Easiest way to convert a List to a Set in JavaChecking for a null int value from a Java ResultSetHow to convert an Array to a Set in JavaConverting 'ArrayList<String> to 'String[]' in JavaHow to convert comma-separated String to ArrayList?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I have query which will return two values(Column A and Column B) as below



A B
------------
a aaa
a aaa
a aaa
a aaa
b bbb
c ccc
c ccc
b bbb
c ccc
b bbb


I am trying to create a java method(Java 7) which will fetch all these value in one go and store it in a collection variable(Map) like all the value in the below format



(a -> (aaa,aaa,aaa,aaa,aaa),
b -> (bbb,bbb,bbb),
c -> (ccc,ccc,ccc))


Below is the method I am trying, but I am not even able to fetch all the data in the first place:



import java.sql.*;
import java.util.ArrayList;

public class CollectionFrame


public static void main(String[] args)

try
// step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");

// step2 create the connection object
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hr", "hr");

// step3 create the statement object
Statement stmt = con.createStatement();

// step4 execute query

// Lists of Lists to store the values
ArrayList<ArrayList<String>> listOLists = new ArrayList<ArrayList<String>>();
ArrayList<String> obj = new ArrayList<String>();

ResultSet rs = stmt.executeQuery("select * from t");
while (rs.next())
// System.out.println(rs.getString(1) + " " + rs.getString(2));
obj.add(rs.getString(1));
// obj.add(rs.getString(2));
listOLists.add(obj);
obj.removeAll(obj);



// step5 close the connection object
con.close();

System.out.println(listOLists.toString());

catch (Exception e)
System.out.println(e);







the above code gives the below result



[[a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b]]


If I uncomment the line obj.removeAll(obj); I get the following:



[[], [], [], [], [], [], [], [], [], []]


I am stuck here. Can someone help me how proceed or suggest a better solution?










share|improve this question



















  • 2





    First to get the correct data, use obj = new ArrayList<String>() inside the while loop

    – YCF_L
    Mar 24 at 16:26












  • "store it in a collection variable(Map)" If you're trying to store values in a Map, how come there is no use of any Map in your code? Re-think what you're doing. You need a Map<String, List<String>> in your code.

    – Andreas
    Mar 24 at 16:27












  • Second, I don't understand what you want to do exactly with your code? do you want to get all columns and group by column A in Java code?

    – YCF_L
    Mar 24 at 16:28











  • Third, I would create an Object which hold A and B column it can be more easy

    – YCF_L
    Mar 24 at 16:29






  • 1





    @YCF_L OP wants a Map<String, List<String>> keys by column A, with list of values from column B. No need for an object for that, just: Map<String, List<String>> map = new HashMap<>(); while (rs.next()) map.computeIfAbsent(rs.getString(1), k -> new ArrayList<>()).add(rs.getString(2)); --- It's curious that OP specifically said a Map is desired, but the code doesn't have any map in it.

    – Andreas
    Mar 24 at 16:32


















0















I have query which will return two values(Column A and Column B) as below



A B
------------
a aaa
a aaa
a aaa
a aaa
b bbb
c ccc
c ccc
b bbb
c ccc
b bbb


I am trying to create a java method(Java 7) which will fetch all these value in one go and store it in a collection variable(Map) like all the value in the below format



(a -> (aaa,aaa,aaa,aaa,aaa),
b -> (bbb,bbb,bbb),
c -> (ccc,ccc,ccc))


Below is the method I am trying, but I am not even able to fetch all the data in the first place:



import java.sql.*;
import java.util.ArrayList;

public class CollectionFrame


public static void main(String[] args)

try
// step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");

// step2 create the connection object
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hr", "hr");

// step3 create the statement object
Statement stmt = con.createStatement();

// step4 execute query

// Lists of Lists to store the values
ArrayList<ArrayList<String>> listOLists = new ArrayList<ArrayList<String>>();
ArrayList<String> obj = new ArrayList<String>();

ResultSet rs = stmt.executeQuery("select * from t");
while (rs.next())
// System.out.println(rs.getString(1) + " " + rs.getString(2));
obj.add(rs.getString(1));
// obj.add(rs.getString(2));
listOLists.add(obj);
obj.removeAll(obj);



// step5 close the connection object
con.close();

System.out.println(listOLists.toString());

catch (Exception e)
System.out.println(e);







the above code gives the below result



[[a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b]]


If I uncomment the line obj.removeAll(obj); I get the following:



[[], [], [], [], [], [], [], [], [], []]


I am stuck here. Can someone help me how proceed or suggest a better solution?










share|improve this question



















  • 2





    First to get the correct data, use obj = new ArrayList<String>() inside the while loop

    – YCF_L
    Mar 24 at 16:26












  • "store it in a collection variable(Map)" If you're trying to store values in a Map, how come there is no use of any Map in your code? Re-think what you're doing. You need a Map<String, List<String>> in your code.

    – Andreas
    Mar 24 at 16:27












  • Second, I don't understand what you want to do exactly with your code? do you want to get all columns and group by column A in Java code?

    – YCF_L
    Mar 24 at 16:28











  • Third, I would create an Object which hold A and B column it can be more easy

    – YCF_L
    Mar 24 at 16:29






  • 1





    @YCF_L OP wants a Map<String, List<String>> keys by column A, with list of values from column B. No need for an object for that, just: Map<String, List<String>> map = new HashMap<>(); while (rs.next()) map.computeIfAbsent(rs.getString(1), k -> new ArrayList<>()).add(rs.getString(2)); --- It's curious that OP specifically said a Map is desired, but the code doesn't have any map in it.

    – Andreas
    Mar 24 at 16:32














0












0








0








I have query which will return two values(Column A and Column B) as below



A B
------------
a aaa
a aaa
a aaa
a aaa
b bbb
c ccc
c ccc
b bbb
c ccc
b bbb


I am trying to create a java method(Java 7) which will fetch all these value in one go and store it in a collection variable(Map) like all the value in the below format



(a -> (aaa,aaa,aaa,aaa,aaa),
b -> (bbb,bbb,bbb),
c -> (ccc,ccc,ccc))


Below is the method I am trying, but I am not even able to fetch all the data in the first place:



import java.sql.*;
import java.util.ArrayList;

public class CollectionFrame


public static void main(String[] args)

try
// step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");

// step2 create the connection object
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hr", "hr");

// step3 create the statement object
Statement stmt = con.createStatement();

// step4 execute query

// Lists of Lists to store the values
ArrayList<ArrayList<String>> listOLists = new ArrayList<ArrayList<String>>();
ArrayList<String> obj = new ArrayList<String>();

ResultSet rs = stmt.executeQuery("select * from t");
while (rs.next())
// System.out.println(rs.getString(1) + " " + rs.getString(2));
obj.add(rs.getString(1));
// obj.add(rs.getString(2));
listOLists.add(obj);
obj.removeAll(obj);



// step5 close the connection object
con.close();

System.out.println(listOLists.toString());

catch (Exception e)
System.out.println(e);







the above code gives the below result



[[a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b]]


If I uncomment the line obj.removeAll(obj); I get the following:



[[], [], [], [], [], [], [], [], [], []]


I am stuck here. Can someone help me how proceed or suggest a better solution?










share|improve this question
















I have query which will return two values(Column A and Column B) as below



A B
------------
a aaa
a aaa
a aaa
a aaa
b bbb
c ccc
c ccc
b bbb
c ccc
b bbb


I am trying to create a java method(Java 7) which will fetch all these value in one go and store it in a collection variable(Map) like all the value in the below format



(a -> (aaa,aaa,aaa,aaa,aaa),
b -> (bbb,bbb,bbb),
c -> (ccc,ccc,ccc))


Below is the method I am trying, but I am not even able to fetch all the data in the first place:



import java.sql.*;
import java.util.ArrayList;

public class CollectionFrame


public static void main(String[] args)

try
// step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");

// step2 create the connection object
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hr", "hr");

// step3 create the statement object
Statement stmt = con.createStatement();

// step4 execute query

// Lists of Lists to store the values
ArrayList<ArrayList<String>> listOLists = new ArrayList<ArrayList<String>>();
ArrayList<String> obj = new ArrayList<String>();

ResultSet rs = stmt.executeQuery("select * from t");
while (rs.next())
// System.out.println(rs.getString(1) + " " + rs.getString(2));
obj.add(rs.getString(1));
// obj.add(rs.getString(2));
listOLists.add(obj);
obj.removeAll(obj);



// step5 close the connection object
con.close();

System.out.println(listOLists.toString());

catch (Exception e)
System.out.println(e);







the above code gives the below result



[[a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b]]


If I uncomment the line obj.removeAll(obj); I get the following:



[[], [], [], [], [], [], [], [], [], []]


I am stuck here. Can someone help me how proceed or suggest a better solution?







collections java-7 resultset






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 24 at 16:55







A_T

















asked Mar 24 at 16:20









A_TA_T

152425




152425







  • 2





    First to get the correct data, use obj = new ArrayList<String>() inside the while loop

    – YCF_L
    Mar 24 at 16:26












  • "store it in a collection variable(Map)" If you're trying to store values in a Map, how come there is no use of any Map in your code? Re-think what you're doing. You need a Map<String, List<String>> in your code.

    – Andreas
    Mar 24 at 16:27












  • Second, I don't understand what you want to do exactly with your code? do you want to get all columns and group by column A in Java code?

    – YCF_L
    Mar 24 at 16:28











  • Third, I would create an Object which hold A and B column it can be more easy

    – YCF_L
    Mar 24 at 16:29






  • 1





    @YCF_L OP wants a Map<String, List<String>> keys by column A, with list of values from column B. No need for an object for that, just: Map<String, List<String>> map = new HashMap<>(); while (rs.next()) map.computeIfAbsent(rs.getString(1), k -> new ArrayList<>()).add(rs.getString(2)); --- It's curious that OP specifically said a Map is desired, but the code doesn't have any map in it.

    – Andreas
    Mar 24 at 16:32













  • 2





    First to get the correct data, use obj = new ArrayList<String>() inside the while loop

    – YCF_L
    Mar 24 at 16:26












  • "store it in a collection variable(Map)" If you're trying to store values in a Map, how come there is no use of any Map in your code? Re-think what you're doing. You need a Map<String, List<String>> in your code.

    – Andreas
    Mar 24 at 16:27












  • Second, I don't understand what you want to do exactly with your code? do you want to get all columns and group by column A in Java code?

    – YCF_L
    Mar 24 at 16:28











  • Third, I would create an Object which hold A and B column it can be more easy

    – YCF_L
    Mar 24 at 16:29






  • 1





    @YCF_L OP wants a Map<String, List<String>> keys by column A, with list of values from column B. No need for an object for that, just: Map<String, List<String>> map = new HashMap<>(); while (rs.next()) map.computeIfAbsent(rs.getString(1), k -> new ArrayList<>()).add(rs.getString(2)); --- It's curious that OP specifically said a Map is desired, but the code doesn't have any map in it.

    – Andreas
    Mar 24 at 16:32








2




2





First to get the correct data, use obj = new ArrayList<String>() inside the while loop

– YCF_L
Mar 24 at 16:26






First to get the correct data, use obj = new ArrayList<String>() inside the while loop

– YCF_L
Mar 24 at 16:26














"store it in a collection variable(Map)" If you're trying to store values in a Map, how come there is no use of any Map in your code? Re-think what you're doing. You need a Map<String, List<String>> in your code.

– Andreas
Mar 24 at 16:27






"store it in a collection variable(Map)" If you're trying to store values in a Map, how come there is no use of any Map in your code? Re-think what you're doing. You need a Map<String, List<String>> in your code.

– Andreas
Mar 24 at 16:27














Second, I don't understand what you want to do exactly with your code? do you want to get all columns and group by column A in Java code?

– YCF_L
Mar 24 at 16:28





Second, I don't understand what you want to do exactly with your code? do you want to get all columns and group by column A in Java code?

– YCF_L
Mar 24 at 16:28













Third, I would create an Object which hold A and B column it can be more easy

– YCF_L
Mar 24 at 16:29





Third, I would create an Object which hold A and B column it can be more easy

– YCF_L
Mar 24 at 16:29




1




1





@YCF_L OP wants a Map<String, List<String>> keys by column A, with list of values from column B. No need for an object for that, just: Map<String, List<String>> map = new HashMap<>(); while (rs.next()) map.computeIfAbsent(rs.getString(1), k -> new ArrayList<>()).add(rs.getString(2)); --- It's curious that OP specifically said a Map is desired, but the code doesn't have any map in it.

– Andreas
Mar 24 at 16:32






@YCF_L OP wants a Map<String, List<String>> keys by column A, with list of values from column B. No need for an object for that, just: Map<String, List<String>> map = new HashMap<>(); while (rs.next()) map.computeIfAbsent(rs.getString(1), k -> new ArrayList<>()).add(rs.getString(2)); --- It's curious that OP specifically said a Map is desired, but the code doesn't have any map in it.

– Andreas
Mar 24 at 16:32













3 Answers
3






active

oldest

votes


















2














You should use a map for this.



ResultSet rs = stmt.executeQuery("select * from t");
Map<String, List<String>> valueMap = new HashMap<>();

while (rs.next())
String columnAstring = rs.getString(1);
String columnBstring = rs.getString(2);

valueMap.putIfAbsent(columnAstring, new ArrrayList<>());
valueMap.get(columnAstring).add(columnBstring);




EDIT: So putifabsent might be quite inefficient since I will be creating and discarding lot of arraylists. as pointed out by @Andreas. So this would be a tiny bit less cleaner but way more efficient way to do it!



Compatible with JAVA 7



ResultSet rs = stmt.executeQuery("select * from t");
Map<String, List<String>> valueMap = new HashMap<>();

while (rs.next())
String columnAstring = rs.getString(1);
String columnBstring = rs.getString(2);

if(!valueMap.containsKey(columnAstring))
valueMap.put(columnAstring, new ArrayList());

valueMao.get(columnA).add(columnBstring);




With Java 8 Lambdas




@Mureinik's answer has pointed out an even cleaner way using
computeIfAbsent.




while (rs.next()) 
String columnAstring = rs.getString(1);
String columnBstring = rs.getString(2);

valueMap.computeIfAbsent(columnAstring, k -> new ArrayList<>())
valueMap.get(columnAstring).add(columnBstring);






share|improve this answer




















  • 1





    Don't use putIfAbsent. Use computeIfAbsent. Your code is unnecessarily creating and discarding a lot of ArrayList objects (only 2 r's, not 3).

    – Andreas
    Mar 24 at 16:35












  • Oh I hadn't thought of that :O.

    – Dehan de Croos
    Mar 24 at 16:36


















1














I'd iterate over the ResultSet and apply the changes to a map Map<String, List<String>>. In each iteration, if the key (column A) doesn't exist, you need to add it with an empty list, and then once you're sure you have a list for that key, append the value from column B. Luckily, Java 8's improvements to the Map interface make this quite elegant:



Map<String, List<String>> result = new HashMap<>();
while (rs.next())
String a = rs.getString("a");
String b = rs.getString("b");

result.computeIfAbsent(a, k -> new ArrayList<>()).add(b);






share|improve this answer























  • Unfortunately , I am doing this POC for Java 7 :( , Sorry I didn't mention that in the question.

    – A_T
    Mar 24 at 16:53


















1














Maybe you can try this. This uses HashMap.



public class Main 
public static void main(String[] args)

//sample CSV strings...pretend they came from a file
String[] csvStrings = new String[]
"a aaa","a aaa","a aaa","a aaa","b bbb","b bbb","b bbb",
"b bbb","c ccc","c ccc","c ccc"
;

List<List<String>> csvList = new ArrayList<List<String>>();
Map<String,ArrayList<String>> outVal
= new HashMap<String, ArrayList<String>>();

for(String val:csvStrings)
String outList[] = val.split(" ");
if (outVal.containsKey(outList[0]))
outVal.get(outList[0]).add(outList[1]);
else
ArrayList<String> inputList = new ArrayList<String>();
inputList.add(outList[1]);
outVal.put(outList[0],inputList);



System.out.println(outVal.toString());





Here's the output:
a=[aaa, aaa, aaa, aaa], b=[bbb, bbb, bbb, bbb], c=[ccc, ccc, ccc]






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55325884%2fconvert-resultset-into-map%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    You should use a map for this.



    ResultSet rs = stmt.executeQuery("select * from t");
    Map<String, List<String>> valueMap = new HashMap<>();

    while (rs.next())
    String columnAstring = rs.getString(1);
    String columnBstring = rs.getString(2);

    valueMap.putIfAbsent(columnAstring, new ArrrayList<>());
    valueMap.get(columnAstring).add(columnBstring);




    EDIT: So putifabsent might be quite inefficient since I will be creating and discarding lot of arraylists. as pointed out by @Andreas. So this would be a tiny bit less cleaner but way more efficient way to do it!



    Compatible with JAVA 7



    ResultSet rs = stmt.executeQuery("select * from t");
    Map<String, List<String>> valueMap = new HashMap<>();

    while (rs.next())
    String columnAstring = rs.getString(1);
    String columnBstring = rs.getString(2);

    if(!valueMap.containsKey(columnAstring))
    valueMap.put(columnAstring, new ArrayList());

    valueMao.get(columnA).add(columnBstring);




    With Java 8 Lambdas




    @Mureinik's answer has pointed out an even cleaner way using
    computeIfAbsent.




    while (rs.next()) 
    String columnAstring = rs.getString(1);
    String columnBstring = rs.getString(2);

    valueMap.computeIfAbsent(columnAstring, k -> new ArrayList<>())
    valueMap.get(columnAstring).add(columnBstring);






    share|improve this answer




















    • 1





      Don't use putIfAbsent. Use computeIfAbsent. Your code is unnecessarily creating and discarding a lot of ArrayList objects (only 2 r's, not 3).

      – Andreas
      Mar 24 at 16:35












    • Oh I hadn't thought of that :O.

      – Dehan de Croos
      Mar 24 at 16:36















    2














    You should use a map for this.



    ResultSet rs = stmt.executeQuery("select * from t");
    Map<String, List<String>> valueMap = new HashMap<>();

    while (rs.next())
    String columnAstring = rs.getString(1);
    String columnBstring = rs.getString(2);

    valueMap.putIfAbsent(columnAstring, new ArrrayList<>());
    valueMap.get(columnAstring).add(columnBstring);




    EDIT: So putifabsent might be quite inefficient since I will be creating and discarding lot of arraylists. as pointed out by @Andreas. So this would be a tiny bit less cleaner but way more efficient way to do it!



    Compatible with JAVA 7



    ResultSet rs = stmt.executeQuery("select * from t");
    Map<String, List<String>> valueMap = new HashMap<>();

    while (rs.next())
    String columnAstring = rs.getString(1);
    String columnBstring = rs.getString(2);

    if(!valueMap.containsKey(columnAstring))
    valueMap.put(columnAstring, new ArrayList());

    valueMao.get(columnA).add(columnBstring);




    With Java 8 Lambdas




    @Mureinik's answer has pointed out an even cleaner way using
    computeIfAbsent.




    while (rs.next()) 
    String columnAstring = rs.getString(1);
    String columnBstring = rs.getString(2);

    valueMap.computeIfAbsent(columnAstring, k -> new ArrayList<>())
    valueMap.get(columnAstring).add(columnBstring);






    share|improve this answer




















    • 1





      Don't use putIfAbsent. Use computeIfAbsent. Your code is unnecessarily creating and discarding a lot of ArrayList objects (only 2 r's, not 3).

      – Andreas
      Mar 24 at 16:35












    • Oh I hadn't thought of that :O.

      – Dehan de Croos
      Mar 24 at 16:36













    2












    2








    2







    You should use a map for this.



    ResultSet rs = stmt.executeQuery("select * from t");
    Map<String, List<String>> valueMap = new HashMap<>();

    while (rs.next())
    String columnAstring = rs.getString(1);
    String columnBstring = rs.getString(2);

    valueMap.putIfAbsent(columnAstring, new ArrrayList<>());
    valueMap.get(columnAstring).add(columnBstring);




    EDIT: So putifabsent might be quite inefficient since I will be creating and discarding lot of arraylists. as pointed out by @Andreas. So this would be a tiny bit less cleaner but way more efficient way to do it!



    Compatible with JAVA 7



    ResultSet rs = stmt.executeQuery("select * from t");
    Map<String, List<String>> valueMap = new HashMap<>();

    while (rs.next())
    String columnAstring = rs.getString(1);
    String columnBstring = rs.getString(2);

    if(!valueMap.containsKey(columnAstring))
    valueMap.put(columnAstring, new ArrayList());

    valueMao.get(columnA).add(columnBstring);




    With Java 8 Lambdas




    @Mureinik's answer has pointed out an even cleaner way using
    computeIfAbsent.




    while (rs.next()) 
    String columnAstring = rs.getString(1);
    String columnBstring = rs.getString(2);

    valueMap.computeIfAbsent(columnAstring, k -> new ArrayList<>())
    valueMap.get(columnAstring).add(columnBstring);






    share|improve this answer















    You should use a map for this.



    ResultSet rs = stmt.executeQuery("select * from t");
    Map<String, List<String>> valueMap = new HashMap<>();

    while (rs.next())
    String columnAstring = rs.getString(1);
    String columnBstring = rs.getString(2);

    valueMap.putIfAbsent(columnAstring, new ArrrayList<>());
    valueMap.get(columnAstring).add(columnBstring);




    EDIT: So putifabsent might be quite inefficient since I will be creating and discarding lot of arraylists. as pointed out by @Andreas. So this would be a tiny bit less cleaner but way more efficient way to do it!



    Compatible with JAVA 7



    ResultSet rs = stmt.executeQuery("select * from t");
    Map<String, List<String>> valueMap = new HashMap<>();

    while (rs.next())
    String columnAstring = rs.getString(1);
    String columnBstring = rs.getString(2);

    if(!valueMap.containsKey(columnAstring))
    valueMap.put(columnAstring, new ArrayList());

    valueMao.get(columnA).add(columnBstring);




    With Java 8 Lambdas




    @Mureinik's answer has pointed out an even cleaner way using
    computeIfAbsent.




    while (rs.next()) 
    String columnAstring = rs.getString(1);
    String columnBstring = rs.getString(2);

    valueMap.computeIfAbsent(columnAstring, k -> new ArrayList<>())
    valueMap.get(columnAstring).add(columnBstring);







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 25 at 16:04

























    answered Mar 24 at 16:34









    Dehan de CroosDehan de Croos

    1,3491221




    1,3491221







    • 1





      Don't use putIfAbsent. Use computeIfAbsent. Your code is unnecessarily creating and discarding a lot of ArrayList objects (only 2 r's, not 3).

      – Andreas
      Mar 24 at 16:35












    • Oh I hadn't thought of that :O.

      – Dehan de Croos
      Mar 24 at 16:36












    • 1





      Don't use putIfAbsent. Use computeIfAbsent. Your code is unnecessarily creating and discarding a lot of ArrayList objects (only 2 r's, not 3).

      – Andreas
      Mar 24 at 16:35












    • Oh I hadn't thought of that :O.

      – Dehan de Croos
      Mar 24 at 16:36







    1




    1





    Don't use putIfAbsent. Use computeIfAbsent. Your code is unnecessarily creating and discarding a lot of ArrayList objects (only 2 r's, not 3).

    – Andreas
    Mar 24 at 16:35






    Don't use putIfAbsent. Use computeIfAbsent. Your code is unnecessarily creating and discarding a lot of ArrayList objects (only 2 r's, not 3).

    – Andreas
    Mar 24 at 16:35














    Oh I hadn't thought of that :O.

    – Dehan de Croos
    Mar 24 at 16:36





    Oh I hadn't thought of that :O.

    – Dehan de Croos
    Mar 24 at 16:36













    1














    I'd iterate over the ResultSet and apply the changes to a map Map<String, List<String>>. In each iteration, if the key (column A) doesn't exist, you need to add it with an empty list, and then once you're sure you have a list for that key, append the value from column B. Luckily, Java 8's improvements to the Map interface make this quite elegant:



    Map<String, List<String>> result = new HashMap<>();
    while (rs.next())
    String a = rs.getString("a");
    String b = rs.getString("b");

    result.computeIfAbsent(a, k -> new ArrayList<>()).add(b);






    share|improve this answer























    • Unfortunately , I am doing this POC for Java 7 :( , Sorry I didn't mention that in the question.

      – A_T
      Mar 24 at 16:53















    1














    I'd iterate over the ResultSet and apply the changes to a map Map<String, List<String>>. In each iteration, if the key (column A) doesn't exist, you need to add it with an empty list, and then once you're sure you have a list for that key, append the value from column B. Luckily, Java 8's improvements to the Map interface make this quite elegant:



    Map<String, List<String>> result = new HashMap<>();
    while (rs.next())
    String a = rs.getString("a");
    String b = rs.getString("b");

    result.computeIfAbsent(a, k -> new ArrayList<>()).add(b);






    share|improve this answer























    • Unfortunately , I am doing this POC for Java 7 :( , Sorry I didn't mention that in the question.

      – A_T
      Mar 24 at 16:53













    1












    1








    1







    I'd iterate over the ResultSet and apply the changes to a map Map<String, List<String>>. In each iteration, if the key (column A) doesn't exist, you need to add it with an empty list, and then once you're sure you have a list for that key, append the value from column B. Luckily, Java 8's improvements to the Map interface make this quite elegant:



    Map<String, List<String>> result = new HashMap<>();
    while (rs.next())
    String a = rs.getString("a");
    String b = rs.getString("b");

    result.computeIfAbsent(a, k -> new ArrayList<>()).add(b);






    share|improve this answer













    I'd iterate over the ResultSet and apply the changes to a map Map<String, List<String>>. In each iteration, if the key (column A) doesn't exist, you need to add it with an empty list, and then once you're sure you have a list for that key, append the value from column B. Luckily, Java 8's improvements to the Map interface make this quite elegant:



    Map<String, List<String>> result = new HashMap<>();
    while (rs.next())
    String a = rs.getString("a");
    String b = rs.getString("b");

    result.computeIfAbsent(a, k -> new ArrayList<>()).add(b);







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Mar 24 at 16:39









    MureinikMureinik

    191k22149214




    191k22149214












    • Unfortunately , I am doing this POC for Java 7 :( , Sorry I didn't mention that in the question.

      – A_T
      Mar 24 at 16:53

















    • Unfortunately , I am doing this POC for Java 7 :( , Sorry I didn't mention that in the question.

      – A_T
      Mar 24 at 16:53
















    Unfortunately , I am doing this POC for Java 7 :( , Sorry I didn't mention that in the question.

    – A_T
    Mar 24 at 16:53





    Unfortunately , I am doing this POC for Java 7 :( , Sorry I didn't mention that in the question.

    – A_T
    Mar 24 at 16:53











    1














    Maybe you can try this. This uses HashMap.



    public class Main 
    public static void main(String[] args)

    //sample CSV strings...pretend they came from a file
    String[] csvStrings = new String[]
    "a aaa","a aaa","a aaa","a aaa","b bbb","b bbb","b bbb",
    "b bbb","c ccc","c ccc","c ccc"
    ;

    List<List<String>> csvList = new ArrayList<List<String>>();
    Map<String,ArrayList<String>> outVal
    = new HashMap<String, ArrayList<String>>();

    for(String val:csvStrings)
    String outList[] = val.split(" ");
    if (outVal.containsKey(outList[0]))
    outVal.get(outList[0]).add(outList[1]);
    else
    ArrayList<String> inputList = new ArrayList<String>();
    inputList.add(outList[1]);
    outVal.put(outList[0],inputList);



    System.out.println(outVal.toString());





    Here's the output:
    a=[aaa, aaa, aaa, aaa], b=[bbb, bbb, bbb, bbb], c=[ccc, ccc, ccc]






    share|improve this answer



























      1














      Maybe you can try this. This uses HashMap.



      public class Main 
      public static void main(String[] args)

      //sample CSV strings...pretend they came from a file
      String[] csvStrings = new String[]
      "a aaa","a aaa","a aaa","a aaa","b bbb","b bbb","b bbb",
      "b bbb","c ccc","c ccc","c ccc"
      ;

      List<List<String>> csvList = new ArrayList<List<String>>();
      Map<String,ArrayList<String>> outVal
      = new HashMap<String, ArrayList<String>>();

      for(String val:csvStrings)
      String outList[] = val.split(" ");
      if (outVal.containsKey(outList[0]))
      outVal.get(outList[0]).add(outList[1]);
      else
      ArrayList<String> inputList = new ArrayList<String>();
      inputList.add(outList[1]);
      outVal.put(outList[0],inputList);



      System.out.println(outVal.toString());





      Here's the output:
      a=[aaa, aaa, aaa, aaa], b=[bbb, bbb, bbb, bbb], c=[ccc, ccc, ccc]






      share|improve this answer

























        1












        1








        1







        Maybe you can try this. This uses HashMap.



        public class Main 
        public static void main(String[] args)

        //sample CSV strings...pretend they came from a file
        String[] csvStrings = new String[]
        "a aaa","a aaa","a aaa","a aaa","b bbb","b bbb","b bbb",
        "b bbb","c ccc","c ccc","c ccc"
        ;

        List<List<String>> csvList = new ArrayList<List<String>>();
        Map<String,ArrayList<String>> outVal
        = new HashMap<String, ArrayList<String>>();

        for(String val:csvStrings)
        String outList[] = val.split(" ");
        if (outVal.containsKey(outList[0]))
        outVal.get(outList[0]).add(outList[1]);
        else
        ArrayList<String> inputList = new ArrayList<String>();
        inputList.add(outList[1]);
        outVal.put(outList[0],inputList);



        System.out.println(outVal.toString());





        Here's the output:
        a=[aaa, aaa, aaa, aaa], b=[bbb, bbb, bbb, bbb], c=[ccc, ccc, ccc]






        share|improve this answer













        Maybe you can try this. This uses HashMap.



        public class Main 
        public static void main(String[] args)

        //sample CSV strings...pretend they came from a file
        String[] csvStrings = new String[]
        "a aaa","a aaa","a aaa","a aaa","b bbb","b bbb","b bbb",
        "b bbb","c ccc","c ccc","c ccc"
        ;

        List<List<String>> csvList = new ArrayList<List<String>>();
        Map<String,ArrayList<String>> outVal
        = new HashMap<String, ArrayList<String>>();

        for(String val:csvStrings)
        String outList[] = val.split(" ");
        if (outVal.containsKey(outList[0]))
        outVal.get(outList[0]).add(outList[1]);
        else
        ArrayList<String> inputList = new ArrayList<String>();
        inputList.add(outList[1]);
        outVal.put(outList[0],inputList);



        System.out.println(outVal.toString());





        Here's the output:
        a=[aaa, aaa, aaa, aaa], b=[bbb, bbb, bbb, bbb], c=[ccc, ccc, ccc]







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 24 at 18:43









        beholdbehold

        321217




        321217



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55325884%2fconvert-resultset-into-map%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript