How to generate HBase java Put class from String Array? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to generate HBase java Put class from String Array? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am newbie on Java 8 lambda and stream programming. This is simple source which generate HBase Put class from String array.

List<String> list = new ArrayList<>(5);
list.add("1," + "colFamily" + ",a,1");
list.add("2," + "colFamily" + ",a,2");
list.add("3," + "colFamily" + ",a,3");
list.add("4," + "colFamily" + ",a,4");
list.add("5," + "colFamily" + ",a,5");

for (int i=0 ; i<list.size() ; i++) {
  String[] cells = list.get(i).split(",");

  Put put = new Put(Bytes.toBytes(cells[0]));
  put.addColumn(Bytes.toBytes(cells[1]),Bytes.toBytes(cells[2]),Bytes.toBytes(cells[3]));

System.out.println(put);

Results are generated correctly like below,

{"totalColumns":1,"row":"1","families":{"colFamily":[{"qualifier":"a","vlen":1,"tag":[],"timestamp":9223372036854775807}]}}
{"totalColumns":1,"row":"2","families":{"colFamily":[{"qualifier":"a","vlen":1,"tag":[],"timestamp":9223372036854775807}]}}
{"totalColumns":1,"row":"3","families":{"colFamily":[{"qualifier":"a","vlen":1,"tag":[],"timestamp":9223372036854775807}]}}
{"totalColumns":1,"row":"4","families":{"colFamily":[{"qualifier":"a","vlen":1,"tag":[],"timestamp":9223372036854775807}]}}
{"totalColumns":1,"row":"5","families":{"colFamily":[{"qualifier":"a","vlen":1,"tag":[],"timestamp":9223372036854775807}]}}

But by using Java 8 stream, I failed to generate the same results, below is the codes.

System.out.println(list.stream().collect(Collectors.mapping(l -> new Put(Bytes.toBytes(l)), Collectors.toList())));

But definitely the above code brings the wrong results.

[{"totalColumns":0,"row":"1,colFamily,a,1","families":{}}, {"totalColumns":0,"row":"2,colFamily,a,2","families":{}}, {"totalColumns":0,"row":"3,colFamily,a,3","families":{}}, {"totalColumns":0,"row":"4,colFamily,a,4","families":{}}, {"totalColumns":0,"row":"5,colFamily,a,5","families":{}}]

I have no idea how to split comma-seperated-Strings to String array using java 8 stream function.

Answer

How about this:

list
.stream()
.map(s -> s.split(","))
.map(cells -> {
    Put put = new Put(Bytes.toBytes(cells[0]));
    put.addColumn(Bytes.toBytes(cells[1]), Bytes.toBytes(cells[2]), Bytes.toBytes(cells[3]));
    return put;
})
.forEach(System.out::println) // or .collect to list
We are here to answer your question about How to generate HBase java Put class from String Array? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji