如何从String Array生成HBase java Put类?

时间:2017-10-28 10:58:03

标签: java arrays java-stream

我是Java 8 lambda和流编程的新手。这是从String数组生成HBase Put类的简单源。

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);

结果生成正确如下,

{"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}]}}

但是通过使用Java 8流,我无法生成相同的结果,下面是代码。

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

但是上面的代码肯定会带来错误的结果。

[{"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":{}}]

我不知道如何使用java 8流函数将逗号分隔的字符串拆分为String数组。

1 个答案:

答案 0 :(得分:1)

这个怎么样:

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