logo
down
shadow

Java getting every second element from array list and using it as value for hash map


Java getting every second element from array list and using it as value for hash map

Content Index :

Java getting every second element from array list and using it as value for hash map
Tag : java , By : kema
Date : December 02 2020, 10:46 PM

hope this fix your issue I have the following text file :
public Map<String, String> Payload1() throws IOException {
    Scanner sc = new Scanner (new File("src/boot/Payload1.txt"));
    Map<String, String> fileMap = new LinkedHashMap<String, String>();
    int counter = 1;
    String key = "";
    while (sc.hasNextLine()) {
        if(counter % 2 != 0) {
            key = sc.nextLine();
        }else {
            fileMap.put(key, sc.nextLine());
        }
        counter++;
    }
    sc.close();
    return fileMap;
}
public Map<String, String> getFileMap(List<String> list){
    Map<String, String> fileMap = new LinkedHashMap<String, String>();
    String key = "";
    for(int x = 0; x < list.size(); x++) {
        if((x + 1 ) % 2 != 0) {
            key = list.get(x);
        }else {
            fileMap.put(key, list.get(x));
        }
    }
    return fileMap;
}

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

How to check if element in groovy array/hash/collection/list?


Tag : arrays , By : snk
Date : March 29 2020, 07:55 AM
help you fix your problem .contains() is the best method for lists, but for maps you will need to use .containsKey() or .containsValue()
[a:1,b:2,c:3].containsValue(3)
[a:1,b:2,c:3].containsKey('a')

Selecting single hash from array where one hash element has the highest value


Tag : ruby , By : Pierre LeBoo
Date : March 29 2020, 07:55 AM
To fix this issue From the following array of hashes, how can I select a single hash where timestamp has the highest value? , Here you can see:
 data.max_by{|e| e["timestamp"] }
 # >> {"id"=>2, "timestamp"=>1383314386, "data"=>"64ed2ed9-763d-443f-a74e-e7f10cbe783e"}

In Perl, how can I access a hash array element, that is itself another hash array?


Tag : perl , By : Techspirit
Date : March 29 2020, 07:55 AM
like below fixes the issue You didn't declare %thisDevice hash and $thisDevice hashref is completely another variable.
Change
$thisDevice{'remote_device_connect_protocol'};
$thisDevice->{'remote_device_connect_protocol'};

Java 1D array list collection .contains or Hash-Map.containsKey speed


Tag : java , By : kgw
Date : March 29 2020, 07:55 AM
Any of those help You can find details on how each is implemented in the java docs. I believe ArrayList will do a linear search. So HashMap is most likely better.

Java Hash map / Array List Count distinct values


Tag : java , By : Ricardo
Date : March 29 2020, 07:55 AM
will be helpful for those in need You could store a Setof productIds per clientId, and just take the size of that. As a Set does not allow duplicate values, this will effectively give you the distinct number of productIds.
Also, I recommend that you give your variables meaningful name instead of col2, k, map... This will make your code more readable.
Map<String, Set<String>> distinctProductsPerClient = new HashMap<String, Set<String>>();
// Process each CSV file line which is now contained within
// the linesList list Array
// Start from 1 to skip the first line
for (int i = 1; i < linesList.size(); i++) {
    String line = linesList.get(i);
    String[] data = line.split(csvSplitBy);
    String productId = data[1];
    String clientId = data[2];
    String date = data[3];

    // Determine if Column 4 has the desired date
    // and count the values
    if (date.contains("10/12/2017"))  {
        if (!distinctProductsPerClient.containsKey(clientId)) {
            distinctProductsPerClient.put(clientId, new HashSet<>());
        }
        distinctProductsPerClient.get(clientId).add(productId);

    }
}

for (final String clientId : distinctProductsPerClient.keySet()) {
    System.out.println(clientId + ": " + distinctProductsPerClient.get(clientId).size());
}
private static class OrderData {

    private final String productName;
    private final String productId;
    private final String clientId;
    private final String date;

    public OrderData(String csvLine) {

        String[] data = csvLine.split("\t");

        this.productName = data[0];
        this.productId = data[1];
        this.clientId = data[2];
        this.date = data[3];

    }

    public String getProductName() {
        return productName;
    }

    public String getProductId() {
        return productId;
    }

    public String getClientId() {
        return clientId;
    }

    public String getDate() {
        return date;
    }
}
Map<String, Set<String>> distinctProductsPerClient2 = linesList.stream()
        .skip(1)
        .map(OrderData::new)
        .collect(groupingBy(OrderData::getClientId, mapping(OrderData::getProductId, toSet())));
Related Posts Related QUESTIONS :
  • Url Problem while Developing on Localhost and deploy on Remote Virtual Server
  • How to identify the missing type id in Jackson error?
  • android data binding error: cannot find symbol
  • Spring Boot application with a jar dependency does not run after maven build
  • Spring Data JPA query , filter ? search engine ? JPQL?
  • Why LiveData returns null in ViewModel?
  • what this line of code mean....new URLClassLoader(new URL[0],getClass().getClassLoader());
  • Why do need to use new Random() instead of just Random Randomnum?
  • I want to access zk components from the java file
  • How do I cast FieldValue.serverTimestamp() to Kotlin/Java Date Class
  • Insertion Sort Double Array with User Input - JAVA
  • Creating 2 dimesional array with user input and find sum of specific columns
  • can not get Advertising ID Provider in android
  • Convert list of Objects to map of properties
  • How to represent an undirected weighted graph in java
  • Return values as array from collection
  • ByteBuddy generic method return cast to concrete type
  • ImageView hides the round corners of the parent
  • Is there a way to find setter method by its getter method or vice versa in a class?
  • Get aggregated list of properties from list of Objects(Java 8)
  • Unable to find a document in Mongodb where exact date match in java
  • UsernamePasswordAuthenticationFilter skips success handler
  • Use Java filter on stream with in a stream filter
  • Default Login not successful in spring boot 2.1.7
  • Adding key value pairs from a file to a Hashmap
  • Rub regex: matching a char except when after by another char
  • Convert Base64 String to String Array
  • Escape Unicode Character 'POPCORN' to HTML Entity
  • An empty JSON field which is a boolean/nullable field in Java model, is getting converted as null
  • Mongo java driver cannot find public constructor for interface
  • How to unit test writing a file to AWS Lambda output stream?
  • How to make a GitHub GraphQL API Call from Java
  • What's the difference between @ComponentScan and @Bean in a context configuration?
  • Expected class or package adding a view using a class
  • can be delete of a element in a static array be O(1)?
  • Instance variable heap or stack ? ( with specific example)
  • Assert progress of ProgressBar in Espresso test
  • How to detect if gson.fromjson() has excess elements
  • I cant generate the proper code to select the a specific filter on a BI dashboard I am working on
  • How to Inject Dependencies into a Servlet Filter with Spring Boot Filter Registration Bean?
  • Thrift types as a Generic
  • Effective algorithm to random 4 unique integers less than a big max such as 100_000
  • Combining or and negation in Java regex?
  • Unable to instantiate default tuplizer Exception
  • Multi-tenant migration to work with quarkus
  • Ignite persisting a Set: Cannot find metadata for object with compact footer
  • Maven cannot resolve Jacob dependency using eclipse
  • testcontainers oracle database container starts before database user is created
  • Launching two spring boot apps in integration test
  • Is there a way to add a HashMap's value that is a integer array into a ArrayList?
  • Is there any way that I can get a parameter in paintComponent?
  • Empty stack with one recursive method and one iterative method
  • What's the behavior of onBackpressureBuffer in RxJava2
  • Java regex can only use 1 quantifier in a lookback (need 2)
  • How to fix error in native query : it is showing syntax error near or at
  • How to retrieve nested object from a document and display it in FirestoreRecyclerOptions?
  • Why not use ListIterator for full LinkedList Operation?
  • Android Webview EvaluateJavascript sometimes does not return a response
  • Matcher java doesn't work but regex seems to be good
  • Finding dimensions of a .gif file
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com