Comparing strings in a Java list to a list

I have sql output with two columns (userID, projectID). There are multiple entries, and none of the entries are empty or empty.

I want to create a list for network simulation that contains 2 columns (userID, userID) where 2 users are listed together if they share projectID

, for example

Input

userID   projectID
  1         201
  1         502
  2         502
  2         101
  3         201
  3         502

      

Output

userID   userID
  1         2
  1         3
  2         3

      

Basically I want the SQL WHERE to compare like

SELECT u1.userID, u2.userID
FROM user_project u1
JOIN user_project u2 ON u1.projectID = u2.projectID

      

but in Java. The resulting tuples can be different or not, and the order of the results does not matter. I cannot directly query the database with this query as I have no access to the db, only access to the output txts.

I think it could probably be done in a for-loop with a HashMap or ArrayList, but is there a more efficient way to do this? or is there a package that allows me to use SQL-like commands on Java objects?

+3


source to share


3 answers


or is there a package that allows me to use SQL-like commands on Java objects?

Yes. Two major libraries come to mind ...



You can also use the Apache Commons CSV library to parse this file into a collection first if you want something that will support multiple formats.

+2


source


You can achieve this result in three steps:

  • Create a hash map ProjectID

    to list UserID

    s
  • For each list of length 2 or more, all pairs, for example with two nested loops
  • Eliminate duplicate pairs from result


The third step can be combined with the second step if you are using a collection that eliminates duplicates such as Set

.

This will be as efficient as it is in terms of performance, since all searches will run in amortized O (1).

+2


source


1) create a HashMap with projectID as KEY and Ordered LinkedList UserID as values. Example:

 PROJECT_ID                    USERID
  201                           1 => 3
  502                           1 => 2 => 3

      

2) once your HashMap is built as above, you can iterate over all the entries in the HashMap one at a time and you can print the output you want. since the linked list we created is ordered, you can loop over the linked list again and print the output in the order you want.

3) you can save the result as strings "12", "13", "23" and you can either sort them or delete duplicate entries.

0


source







All Articles